/*
This file contains JavaScript functions to convert ASCII math notation
to Presentation MathML. The conversion is done while the XHTML page 
loads, and should work with IE 6+MathPlayer and Mozilla/Netscape 7+.
This is a convenient and inexpensive solution for authoring MathML.

Version 0.9 Dec 28 2003, (c) Peter Jipsen http://www.chapman.edu/~jipsen
Freely available for noncommercial use WITH ABSOLUTELY NO WARRANTY OF ANY KIND.
Contact jipsen@chapman.edu for the latest version.
*/
// still have to handle matrices and piecewise functions

if (document.getElementById==null) 
  alert("This webpage requires a recent browser such as\
\nMozilla/Netscape 7+ or Internet Explorer 6+MathPlayer")

mathcolor = "Red"; // change it to Black if you prefer that
mathdelimit = "`"; // change it to $ if you prefer TeX

symbols = [
//some greek symbols
{input:"alpha",  tag:"mi", output:"\u03B1"},
{input:"beta",   tag:"mi", output:"\u03B2"},
{input:"chi",    tag:"mi", output:"\u03C7"},
{input:"delta",  tag:"mi", output:"\u03B4"},
{input:"Delta",  tag:"mi", output:"\u0394"},
{input:"epsilon", tag:"mi", output:"\u03B5", tex:"varepsilon"},
{input:"eta",    tag:"mi", output:"\u03B7"},
{input:"gamma",  tag:"mi", output:"\u03B3"},
{input:"Gamma",  tag:"mi", output:"\u0393"},
{input:"iota",   tag:"mi", output:"\u03B9"},
{input:"kappa",  tag:"mi", output:"\u03BA"},
{input:"lambda", tag:"mi", output:"\u03BB"},
{input:"Lambda", tag:"mi", output:"\u039B"},
{input:"mu",     tag:"mi", output:"\u03BC"},
{input:"nu",     tag:"mi", output:"\u03BD"},
{input:"omega",  tag:"mi", output:"\u03C9"},
{input:"Omega",  tag:"mi", output:"\u03A9"},
{input:"phi",    tag:"mi", output:"\u03C6"},
{input:"varphi", tag:"mi", output:"\u03C6"},
{input:"Phi",    tag:"mi", output:"\u03A6"},
{input:"pi",     tag:"mi", output:"\u03C0"},
{input:"Pi",     tag:"mi", output:"\u03A0"},
{input:"psi",    tag:"mi", output:"\u03C8"},
{input:"rho",    tag:"mi", output:"\u03C1"},
{input:"sigma",  tag:"mi", output:"\u03C3"},
{input:"Sigma",  tag:"mi", output:"\u03A3"},
{input:"tau",    tag:"mi", output:"\u03C4"},
{input:"theta",  tag:"mi", output:"\u03B8"},
{input:"Theta",  tag:"mi", output:"\u0398"},
{input:"upsilon", tag:"mi", output:"\u03C5"},
{input:"xi",     tag:"mi", output:"\u03BE"},
{input:"Xi",     tag:"mi", output:"\u039E"},
{input:"zeta",   tag:"mi", output:"\u03B6"},

//binary operation symbols
{input:"*",  tag:"mo", output:"\u22C5", tex:"cdot"},
{input:"star", tag:"mo", output:"*"},
{input:"//", tag:"mo", output:"/"},
{input:"\\\\",  tag:"mo", output:"\\"},
{input:"xx", tag:"mo", output:"\u00D7", tex:"times"},
{input:"-:", tag:"mo", output:"\u00F7", tex:"divide"},
{input:"@",  tag:"mo", output:"\u2218", tex:"circ"},
{input:"o+", tag:"mo", output:"\u2295", tex:"oplus"},
{input:"ox", tag:"mo", output:"\u2297", tex:"otimes"},
{input:"^^", tag:"mo", output:"\u2227", tex:"wedge"},
{input:"vv", tag:"mo", output:"\u2228", tex:"vee"},
{input:"uu", tag:"mo", output:"\u222A", tex:"cup"},
{input:"union", tag:"mo", output:"\u222A"},
{input:"nn", tag:"mo", output:"\u2229", tex:"cap"},
{input:"intersect", tag:"mo", output:"\u2229"},

//binary relation symbols
{input:"!=",  tag:"mo", output:"\u2260", tex:"ne"},
{input:"lt",  tag:"mo", output:"<"},
{input:"<=",  tag:"mo", output:"\u2264", tex:"le"},
{input:"lt=", tag:"mo", output:"\u2264"},
{input:">=",  tag:"mo", output:"\u2265", tex:"ge"},
{input:"-<",  tag:"mo", output:"\u227A", tex:"prec"},
{input:"-lt", tag:"mo", output:"\u227A"},
{input:">-",  tag:"mo", output:"\u227B", tex:"succ"},
{input:"in",  tag:"mo", output:"\u2208"},
{input:"notin", tag:"mo", output:"\u2209"},
{input:"subset", tag:"mo", output:"\u2286", tex:"subseteq"},
{input:"supset", tag:"mo", output:"\u2287", tex:"supseteq"},
{input:"-=",  tag:"mo", output:"\u2261", tex:"equiv"},
{input:"~=",  tag:"mo", output:"\u2245", tex:"cong"},
{input:"~~",  tag:"mo", output:"\u2248", tex:"approx"},

//logical symbols
{input:"and", tag:"mtext", output:"\u00A0and\u00A0"},
{input:"or",  tag:"mtext", output:"\u00A0or\u00A0"},
{input:"not", tag:"mo", output:"\u00AC", tex:"neg"},
{input:"=>",  tag:"mo", output:"\u21D2", tex:"implies"},
{input:"if",  tag:"mo", output:"\u00A0if\u00A0"},
{input:"iff", tag:"mo", output:"\u21D4"},
{input:"AA",  tag:"mo", output:"\u2200", tex:"forall"},
{input:"EE",  tag:"mo", output:"\u2203", tex:"exists"},
{input:"_|_", tag:"mo", output:"\u22A5"},
{input:"TT",  tag:"mo", output:"\u22A4"},

//grouping brackets
{input:"(", tag:"mo", output:"(", leftBracket:true},
{input:")", tag:"mo", output:")", rightBracket:true},
{input:"[", tag:"mo", output:"[", leftBracket:true},
{input:"]", tag:"mo", output:"]", rightBracket:true},
{input:"{", tag:"mo", output:"{", leftBracket:true},
{input:"}", tag:"mo", output:"}", rightBracket:true},
{input:"(:", tag:"mo", output:"\u2329", leftBracket:true, tex:"langle"},
{input:":)", tag:"mo", output:"\u232A", rightBracket:true, tex:"rangle"},

//miscellaneous symbols
{input:"sum",  tag:"mo", output:"\u2211", underover:"true"},
{input:"prod", tag:"mo", output:"\u220F", underover:"true"},
{input:"int",  tag:"mo", output:"\u222B"},
{input:"del",  tag:"mo", output:"\u2202", tex:"partial"},
{input:"+-",   tag:"mo", output:"\u00B1", tex:"pm"},
{input:"O/",   tag:"mo", output:"\u2205", tex:"emptyset"},
{input:"oo",   tag:"mo", output:"\u221E", tex:"infty"},
{input:"aleph", tag:"mo", output:"\u2135"},
{input:"...",  tag:"mo", output:"...", tex:"ldots"},
{input:"quad", tag:"mo", output:"\u00A0\u00A0"},
{input:"qquad", tag:"mo", output:"\u00A0\u00A0\u00A0\u00A0"},
{input:"cdots", tag:"mo", output:"\u22EF"},
{input:"diamond", tag:"mo", output:"\u22C4"},
{input:"square", tag:"mo", output:"\u25A1"},
{input:"|_", tag:"mo", output:"\u230A", tex:"lfloor"},
{input:"_|", tag:"mo", output:"\u230B", tex:"rfloor"},
{input:"|~", tag:"mo", output:"\u2308", tex:"lceiling"},
{input:"~|", tag:"mo", output:"\u2309", tex:"rceiling"},
{input:"CC",  tag:"mo", output:"\u2102"},
{input:"NN",  tag:"mo", output:"\u2115"},
{input:"QQ",  tag:"mo", output:"\u211A"},
{input:"RR",  tag:"mo", output:"\u211D"},
{input:"ZZ",  tag:"mo", output:"\u2124"},

//standard functions
{input:"lim",  tag:"mo", output:"lim", underover:"true"},
{input:"sin",  tag:"mo", output:"sin"},
{input:"cos",  tag:"mo", output:"cos"},
{input:"tan",  tag:"mo", output:"tan"},
{input:"sinh", tag:"mo", output:"sinh"},
{input:"cosh", tag:"mo", output:"cosh"},
{input:"tanh", tag:"mo", output:"tanh"},
{input:"cot",  tag:"mo", output:"cot"},
{input:"sec",  tag:"mo", output:"sec"},
{input:"csc",  tag:"mo", output:"csc"},
{input:"log",  tag:"mo", output:"log"},
{input:"ln",   tag:"mo", output:"ln"},
{input:"det",  tag:"mo", output:"det"},
{input:"dim",  tag:"mo", output:"dim"},
{input:"mod",  tag:"mo", output:"mod"},

//abbreviations (add your own if you wish)

//arrows
{input:"uarr", tag:"mo", output:"\u2191", tex:"uparrow"},
{input:"darr", tag:"mo", output:"\u2193", tex:"downarrow"},
{input:"rarr", tag:"mo", output:"\u2192", tex:"rightarrow"},
{input:"->",   tag:"mo", output:"\u2192", tex:"to"},
{input:"larr", tag:"mo", output:"\u2190", tex:"leftarrow"},
{input:"harr", tag:"mo", output:"\u2194", tex:"leftrightarrow"},
{input:"rArr", tag:"mo", output:"\u21D2", tex:"Rightarrow"},
{input:"lArr", tag:"mo", output:"\u21D0", tex:"Leftarrow"},
{input:"hArr", tag:"mo", output:"\u21D4", tex:"Leftrightarrow"},

//commands with argument
sqrt = {input:"sqrt", tag:"msqrt", output:"sqrt", unary:true},
root = {input:"root", tag:"mroot", output:"root", binary:true},
frac = {input:"frac", tag:"mfrac", output:"/", binary:true},
div = {input:"/", tag:"mfrac", output:"/", infix:true},
sub = {input:"_", tag:"msub",  output:"_", infix:true},
sup = {input:"^", tag:"msup",  output:"^", infix:true},
text = {input:"text", tag:"mtext", output:"text", unary:true},
mbox = {input:"mbox", tag:"mtext", output:"mbox", unary:true},
{input:"bb", tag:"mstyle", atname:"fontweight", atval:"bold", output:"bb", unary:true},
{input:"mathbf", tag:"mstyle", atname:"fontweight", atval:"bold", output:"mathbf", unary:true},
{input:"bbb", tag:"mstyle", atname:"mathvariant", atval:"double-struck", output:"bbb", unary:true},
{input:"mathbb", tag:"mstyle", atname:"mathvariant", atval:"double-struck", output:"mathbb", unary:true},
{input:"cc",  tag:"mstyle", atname:"mathvariant", atval:"script", output:"cal", unary:true},
{input:"mathcal", tag:"mstyle", atname:"mathvariant", atval:"script", output:"mathcal", unary:true},
{input:"tt",  tag:"mstyle", atname:"fontfamily", atval:"monospace", output:"tt", unary:true},
{input:"mathtt", tag:"mstyle", atname:"fontfamily", atval:"monospace", output:"mathtt", unary:true},
{input:"fr",  tag:"mstyle", atname:"mathvariant", atval:"fraktur", output:"fr", unary:true},
{input:"mathfr",  tag:"mstyle", atname:"mathvariant", atval:"fraktur", output:"mathfr", unary:true}
];

function compareNames(s1,s2) {
  if (s1.input > s2.input) return 1
  else return -1;
}

names = []; //list of input symbols

function initSymbols() {
  var texsymbols = [];
  for (var i=0; i<symbols.length; i++)
    if (symbols[i].tex) 
      texsymbols[texsymbols.length] = 
        {input:symbols[i].tex, tag:"mo", output:symbols[i].output};
  symbols = symbols.concat(texsymbols);
  symbols.sort(compareNames);
  for (var i=0; i<symbols.length; i++) names[i] = symbols[i].input;
}

initSymbols();

function myCreateElementXHTML(t) {
  if (document.createElementNS==null)
    return document.createElement(t);
  else
    return document.createElementNS("http://www.w3.org/1999/xhtml",t);
}

function myCreateElementMathML(t) {
  if (document.createElementNS==null)
    return document.createElement("mml:"+t);
  else
    return document.createElementNS("http://www.w3.org/1998/Math/MathML",t);
}

function createMmlNode(name,frag) {
  var node = myCreateElementMathML(name);
  node.appendChild(frag);
  return node;
}

function removeCharsAndBlanks(str,n) {
//remove n characters and any following blanks
  var st;
  if (str.charAt(n)=="\\" && str.charAt(n+1)!="\\") st = str.slice(n+1);
  else st = str.slice(n);
  for (var i=0; i<st.length && st.charCodeAt(i)<=32; i=i+1);
  return st.slice(i);
}

function position(arr, str, n) { 
// return position >=n where str appears or would be inserted
// assumes arr is sorted
  if (n==0) {
    var h,m;
    n = -1;
    h = arr.length;
    while (n+1<h) {
      m = (n+h) >> 1;
      if (arr[m]<str) n = m; else h = m;
    }
    return h;
  } else
    for (var i=n; i<arr.length && arr[i]<str; i++);
  return i; // i=arr.length || arr[i]>=str
}

function getSymbol(str) {
//return maximal initial substring of str that appears in names
//return null if there is none
  var k = 0; //new pos
  var j = 0; //old pos
  var mk; //match pos
  var st;
  var tagst;
  var match = "";
  var more = true;
  for (var i=1; i<=str.length && more; i++) {
    st = str.slice(0,i); //initial substring of length i
    j = k;
    k = position(names, st, j);
    if (k<names.length && str.slice(0,names[k].length)==names[k]){
      match = names[k];
      mk = k;
      i = match.length;
    }
    more = k<names.length && str.slice(0,names[k].length)>=names[k];
  }
  if (match!="") return symbols[mk]; 
// if str[0] is a digit or - return maxsubstring of digits.digits
  k = 1;
  st = str.slice(0,1);
  var pos = true;
  var integ = true;
  if (st == "-") {
    pos = false;
    st = str.slice(k,k+1);
    k++;
  }
  while ("0"<=st && st<="9" && k<=str.length) {
    st = str.slice(k,k+1);
    k++;
  }
  if (st == ".") {
    integ = false;
    st = str.slice(k,k+1);
    k++;
    while ("0"<=st && st<="9" && k<=str.length) {
      st = str.slice(k,k+1);
      k++;
    }
  }
  if ((pos && integ && k>1) || ((pos || integ) && k>2) || k>3) {
    st = str.slice(0,k-1);
    tagst = "mn";
  } else {
    k = 2;
    st = str.slice(0,1); //take 1 non-letter character
    tagst = (("A"<=st && st<="Z") || ("a"<=st && st<="z")?"mi":"mo");
  }
  return {input:str.slice(0,k-1), tag:tagst, output:st};
}

function removeBrackets(node) {
  if (node.nodeName=="mrow") {
    var st = node.firstChild.firstChild.nodeValue;
    if (st=="(" || st=="[" || st=="{") node.removeChild(node.firstChild);
  }
  if (node.nodeName=="mrow") {
    var st = node.lastChild.firstChild.nodeValue;
    if (st==")" || st=="]" || st=="}") node.removeChild(node.lastChild);
  }
}

/*
Parsing ASCII math expressions with the following grammar

c ::= greek letters | [A-z] | [0-9]+ | other constant symbols (see below)
u ::= "sqrt" | "text" | "bb" | other unary symbols for font commands
b ::= "frac" | "root"          binary symbols
i ::= _ | ^ | /                infix symbols: subscript, superscript, division
l ::= ( | [ | { | (:           left brackets
r ::= ) | ] | } | :)           right brackets
S ::= c | lEr | uS' | bS'S'    simple expression: S' is S with brackets removed
E ::= SE | SiS' | S_S'^S'      expression

Each terminal symbol is translated into a corresponding mathml node.
*/

function parseSexpr(str) { //parses str and returns [node,tailstr]
  var symbol;
  var node,node1;
  var result;
  str = removeCharsAndBlanks(str,0);
  symbol = getSymbol(str);             //either a token or a bracket or empty
  if (symbol == null || symbol.rightBracket)
    return [null,str];
  str = removeCharsAndBlanks(str,symbol.input.length); 
  if (symbol.leftBracket) {                     //read (expr+)
    result = parseExpr(str);
    node = createMmlNode("mo",document.createTextNode(symbol.output));
    node = createMmlNode("mrow",node);
    node.appendChild(result[0]);
    return [node,result[1]];
  }
  else if (symbol.unary) {
    if (symbol == sqrt) {
      result = parseSexpr(str);
      removeBrackets(result[0]);
      return [createMmlNode(symbol.tag,result[0]),result[1]];
    } else if (symbol == text || symbol == mbox) {
    } else {
      result = parseSexpr(str);
      removeBrackets(result[0]);
      node = createMmlNode(symbol.tag,result[0]);
      node.setAttribute(symbol.atname,symbol.atval);
      return [node,result[1]];
    }
  }
  else if (symbol.binary) {
    var newFrag = document.createDocumentFragment();
    result = parseSexpr(str);
    removeBrackets(result[0]);
    var result2 = parseSexpr(result[1]);
    removeBrackets(result2[0]);
    if (symbol==root) newFrag.appendChild(result2[0]);
    newFrag.appendChild(result[0]);
    if (symbol==frac) newFrag.appendChild(result2[0]);
    return [createMmlNode(symbol.tag,newFrag),result2[1]];
  }
  else if (symbol.infix)
    return [createMmlNode("mo",document.createTextNode(symbol.output)),str];
  else return [createMmlNode(symbol.tag,        //its a constant
                             document.createTextNode(symbol.output)),str];
}

function parseExpr(str) {
  var symbol,sym1,sym2;
  var node;
  var result;
  var newFrag = document.createDocumentFragment();
  var nodeList = [];
  do {
    str = removeCharsAndBlanks(str,0);
    sym1 = getSymbol(str);
    result = parseSexpr(str);
    node = result[0];
    str = result[1];
    symbol = getSymbol(str);
    if (symbol.infix) {
      str = removeCharsAndBlanks(str,symbol.input.length);
      result = parseSexpr(str);
      removeBrackets(result[0]);
      str = result[1];
      if (symbol == div) removeBrackets(node);
      if (symbol == sub) {
        sym2 = getSymbol(str);
        if (sym2 == sup) {
          str = removeCharsAndBlanks(str,sym2.input.length);
          var res2 = parseSexpr(str);
          removeBrackets(res2[0]);
          str = res2[1];
            node = createMmlNode((sym1.underover?"munderover":"msubsup"),node);
            node.appendChild(result[0]);
            node.appendChild(res2[0]);
            node = createMmlNode("mrow",node);          
        } else {
          node = createMmlNode((sym1.underover?"munder":"msub"),node);
          node.appendChild(result[0]);
        }
      } else {
        node = createMmlNode(symbol.tag,node);
        node.appendChild(result[0]);
      }
      newFrag.appendChild(node);
    } 
    else if (node!=undefined) newFrag.appendChild(node);
  } while (!symbol.rightBracket && !(symbol==null) && symbol.output!="");
  if (symbol.rightBracket) {
    str = removeCharsAndBlanks(str,symbol.input.length);
    node = createMmlNode("mo",document.createTextNode(symbol.output));
    newFrag.appendChild(node);
  }
  return [newFrag,str];
}

function parseMath(str) {
  var node = myCreateElementMathML("mstyle");
  node.setAttribute("mathcolor",mathcolor);
  node.setAttribute("displaystyle","true");
  node.appendChild(parseExpr(str)[0]);
  return createMmlNode("math",node);
}

function strarr2docFrag(arr) { // should return a document fragment
  var newFrag = document.createDocumentFragment();
  var expr = false;
  for (var i=0; i<arr.length; i++) {
    if (expr) newFrag.appendChild(parseMath(arr[i]));
    else {
      var arri = arr[i].split("\n\n");
      newFrag.appendChild(myCreateElementXHTML("span").
        appendChild(document.createTextNode(arri[0])));
      for (var j=1; j<arri.length; j++) {
        newFrag.appendChild(myCreateElementXHTML("p"));
        newFrag.appendChild(myCreateElementXHTML("span").
          appendChild(document.createTextNode(arri[j])));
      }
    }
    expr = !expr;
  }
  return newFrag;
}

function processNode(n) {
  if (n.childNodes.length == 0 && 
    n.parentNode.nodeName!="pre" && n.parentNode.nodeName!="PRE" &&
    n.parentNode.nodeName!="textarea" && n.parentNode.nodeName!="TEXTAREA") {
    var str = n.nodeValue;
//alert(str);
    if (!(str == null)) {
      var arr = str.split(mathdelimit);
      if (arr.length > 1) n.parentNode.replaceChild(strarr2docFrag(arr),n);
    }
  } else {
    var num = n.childNodes.length;
    processNode(n.childNodes[0]);
    for (var i=1; i<num; i++)
      processNode(n.childNodes[i]);
  }
}

function translate() {
  body = document.getElementsByTagName("body")[0];
  processNode(body);
}

function display() {
  var str = document.getElementById("inputText").value;
  var outnode = document.getElementById("outputNode");
  var n = outnode.childNodes.length;
  for (var i=0; i<n; i++)
    outnode.removeChild(outnode.firstChild);
  outnode.appendChild(document.createTextNode(str));
  processNode(outnode);
}
