/* ASCIIsvg.js
==============
JavaScript routines to dynamically generate Scalable Vector Graphics
using a mathematical xy-coordinate system (y increases upwards) and
very intuitive JavaScript commands (no programming experience required).
ASCIIsvg.js is good for learning math and illustrating online math texts.
Works with Internet Explorer+Adobe SVGviewer and SVG enabled Mozilla/Firefox.

Ver 1.0 April 20, 2004 (c) Peter Jipsen http://www.chapman.edu/~jipsen
Latest version at http://www.chapman.edu/~jipsen/svg/ASCIIsvg.js
If you use it on a webpage, please send the URL to jipsen@chapman.edu

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 2 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 (at http://www.gnu.org/copyleft/gpl.html) 
for more details.*/

xunitlength = 20;  // pixels
yunitlength = 20;  // pixels
origin = [0,0];   // in pixels (default is bottom left corner)
border = 25;
strokewidth = "1" // pixel
stroke = "black"; // default line color
fill = "none";    // default fill color
fontstyle = "italic"; // default shape for text labels
fontfamily = "times"; // default font
fontsize = "20";      // default size

markerstrokewidth = "1";
markerstroke = "black";
markerfill = "yellow";
marker = "none";
arrowfill = stroke;
axesstroke = "black";
pointerpos = null;
coordinates = null;
above = "above";
below = "below";
left = "left";
right = "right";
aboveleft = "aboveleft";
aboveright = "aboveright";
belowleft = "belowleft";
belowright = "belowright";

isIE = document.createElementNS==null;

function less(x,y) { return x < y }

function setText(st,id) { 
  document.getElementById(id).childNodes[0].nodeValue = st;
}

function myCreateElementSVG(t) {
  if (isIE) return doc.createElement(t);
  else return doc.createElementNS("http://www.w3.org/2000/svg",t);
}

function getX() {
  return (doc.getElementById("pointerpos").getAttribute("cx")-origin[0])/xunitlength;
}

function getY() {
  return (height-origin[1]-doc.getElementById("pointerpos").getAttribute("cy"))/yunitlength;
}

function mousemove_listener(evt) {
  if (svgpicture.getAttribute("xbase")!=null)
    pointerpos.cx.baseVal.value = evt.clientX-svgpicture.getAttribute("xbase");
  if (svgpicture.getAttribute("ybase")!=null)
    pointerpos.cy.baseVal.value = evt.clientY-svgpicture.getAttribute("ybase");
}

function top_listener(evt) {
  svgpicture.setAttribute("ybase",evt.clientY);
}

function bottom_listener(evt) { 
  svgpicture.setAttribute("ybase",evt.clientY-height+1);
}

function left_listener(evt) {
  svgpicture.setAttribute("xbase",evt.clientX);
}

function right_listener(evt) {
  svgpicture.setAttribute("xbase",evt.clientX-width+1);
}

function switchTo(id) {
  picture = document.getElementById(id);
  width = picture.getAttribute("width")-0;
  height = picture.getAttribute("height")-0;
  strokewidth = "1" // pixel
  stroke = "black"; // default line color
  fill = "none";    // default fill color
  marker = "none";
  if ((picture.nodeName == "EMBED" || picture.nodeName == "embed") && isIE) {
    svgpicture = picture.getSVGDocument().getElementById("root");
    doc = picture.getSVGDocument();
  } else {
    svgpicture = picture;
    doc = document;
  }
  xunitlength = svgpicture.getAttribute("xunitlength")-0;
  yunitlength = svgpicture.getAttribute("yunitlength")-0;
  origin = [svgpicture.getAttribute("ox")-0,svgpicture.getAttribute("oy")-0];
}

var inlineSVGwindowTimeoutId = null;

function loadSVG(id){
alert(id);
  window.clearInterval(inlineSVGwindowTimeoutId);
  eocount = 0;
  if (document.all(id).readyState == "complete"){
    var svgdoc = document.getElementById(id).getSVGDocument();
    if (typeof(svgdoc) == "object"){
      try{
        var loaded = svgdoc.getElementById("text").firstChild.nodeValue;
        if (loaded == "Loaded")
alert("Worked");
      }catch(e){eocount++;}
    }
  }
  if (eocount > 0)
    inlineSVGwindowTimeoutId = window.setInterval(loadSVG(name), 300); // 100 milliseconds
}

function initPicture(name,xmin,xmax,ymin,ymax) {
  strokewidth = "1" // pixel
  stroke = "black"; // default line color
  fill = "none";    // default fill color
  marker = "none";
  picture = document.getElementById(name);
  width = picture.getAttribute("width")-0;
  height = picture.getAttribute("height")-0;
  if (xmax!=null) {
    xunitlength = (width-2*border)/(xmax-xmin);
    yunitlength = xunitlength;
    if (ymin==null) origin = [-xmin*xunitlength+border,height/2];
    else {
      if (ymax!=null) yunitlength = (height-2*border)/(ymax-ymin);
      origin = [-xmin*xunitlength+border,-ymin*yunitlength+border];
    }
  }
  border = 25;
//  if (picture.nodeName == "EMBED" || picture.nodeName == "embed") {
    if (isIE) {
      picture.outerHTML = "<embed height=\"" + picture.height + "\" width=\"" + picture.width + "\" type=\"image/svg-xml\" src=\"dynamic2.svg\" id=\"" + name + "\">";
      if (inlineSVGwindowTimeoutId == null)
        inlineSVGwindowTimeoutId = window.setInterval(loadSVG(name), 300);
      svgpicture = picture.getSVGDocument().getElementById("root");
      doc = picture.getSVGDocument();
    } else {
      svgpicture = picture;
      doc = document;
      pointerpos = doc.getElementById("pointerpos");
      if (pointerpos==null) {
        pointerpos = myCreateElementSVG("circle");
        pointerpos.setAttribute("id","pointerpos");
        pointerpos.setAttribute("cx",0);
        pointerpos.setAttribute("cy",0);
        pointerpos.setAttribute("r",0.5);
        pointerpos.setAttribute("fill","red");
        svgpicture.appendChild(pointerpos);
      }
    }
//  } else {
//    svgpicture = picture;
//    doc = document;
//  }
  svgpicture.setAttribute("xunitlength",xunitlength);
  svgpicture.setAttribute("yunitlength",yunitlength);
  svgpicture.setAttribute("ox",origin[0]);
  svgpicture.setAttribute("oy",origin[1]);
  var node = myCreateElementSVG("rect");
  node.setAttribute("x","0");
  node.setAttribute("y","0");
  node.setAttribute("width",width);
  node.setAttribute("height",height);
  node.setAttribute("style","stroke-width:1;fill:white");
  svgpicture.appendChild(node);
  if (!isIE && picture.getAttribute("onmousemove")!=null) {
    svgpicture.addEventListener("mousemove", mousemove_listener, true);
    var st = picture.getAttribute("onmousemove");
    svgpicture.addEventListener("mousemove", eval(st.slice(0,st.length-2)), true);
    node = myCreateElementSVG("polyline");
    node.setAttribute("points","0,0 "+width+",0");
    node.setAttribute("style","stroke:white; stroke-width:3");
    node.addEventListener("mousemove", top_listener, true);
    svgpicture.appendChild(node);
    node = myCreateElementSVG("polyline");
    node.setAttribute("points","0,"+height+" "+width+","+height);
    node.setAttribute("style","stroke:white; stroke-width:3");
    node.addEventListener("mousemove", bottom_listener, true);
    svgpicture.appendChild(node);
    node = myCreateElementSVG("polyline");
    node.setAttribute("points","0,0 0,"+height);
    node.setAttribute("style","stroke:white; stroke-width:3");
    node.addEventListener("mousemove", left_listener, true);
    svgpicture.appendChild(node);
    node = myCreateElementSVG("polyline");
    node.setAttribute("points",(width-1)+",0 "+(width-1)+","+height);
    node.setAttribute("style","stroke:white; stroke-width:3");
    node.addEventListener("mousemove", right_listener, true);
    svgpicture.appendChild(node);
  }
  var mnode = doc.getElementById("dot");
  if (mnode==null) {
    node = myCreateElementSVG("defs");
    mnode = myCreateElementSVG("marker");
    mnode.setAttribute("id","dot");
    node.appendChild(mnode);
    svgpicture.appendChild(node);
  }
  mnode.setAttribute("viewBox","-5 -5 10 10");
  mnode.setAttribute("markerWidth","10");
  mnode.setAttribute("markerHeight","10");
  var node = myCreateElementSVG("circle");
  node.setAttribute("cx","0");
  node.setAttribute("cy","0");
  node.setAttribute("r","4");
  node.setAttribute("stroke-width", markerstrokewidth);
  node.setAttribute("stroke", markerstroke);
  node.setAttribute("fill", markerfill);
  mnode.appendChild(node);
  var mnode = doc.getElementById("arrow");
  if (mnode==null) {
    var node = myCreateElementSVG("defs");
    mnode = myCreateElementSVG("marker");
    mnode.setAttribute("id","arrow");
    node.appendChild(mnode);
    svgpicture.appendChild(node);
  }
  mnode.setAttribute("viewBox","0 0 15 10");
  mnode.setAttribute("refX","15");
  mnode.setAttribute("refY","5");
  mnode.setAttribute("markerWidth","15");
  mnode.setAttribute("markerHeight","10");
  mnode.setAttribute("orient","auto")
  var node = myCreateElementSVG("path");
  node.setAttribute("d","M 0 1 L 12 5 L 0 9 z");
  node.setAttribute("stroke-width", markerstrokewidth);
  node.setAttribute("stroke", markerstroke);
  node.setAttribute("fill", arrowfill);
  mnode.appendChild(node);
  var mnode = doc.getElementById("arrowdot");
  if (mnode==null) {
    var node = myCreateElementSVG("defs");
    mnode = myCreateElementSVG("marker");
    mnode.setAttribute("id","arrow");
    node.appendChild(mnode);
    svgpicture.appendChild(node);
  }
  mnode.setAttribute("viewBox","0 0 20 10");
  mnode.setAttribute("refX","15");
  mnode.setAttribute("refY","5");
  mnode.setAttribute("markerWidth","20");
  mnode.setAttribute("markerHeight","10");
  mnode.setAttribute("orient","auto")
  var node = myCreateElementSVG("path");
  node.setAttribute("d","M 0 1 L 12 5 L 0 9 z");
  node.setAttribute("stroke-width", markerstrokewidth);
  node.setAttribute("stroke", markerstroke);
  node.setAttribute("fill", arrowfill);
  mnode.appendChild(node);
  node = myCreateElementSVG("circle");
  node.setAttribute("cx","15");
  node.setAttribute("cy","5");
  node.setAttribute("r","4");
  node.setAttribute("stroke-width", markerstrokewidth);
  node.setAttribute("stroke", markerstroke);
  node.setAttribute("fill", markerfill);
  mnode.appendChild(node);
}

function line(p,q,id) { // segment connecting points p,q (coordinates in units)
  var node;
  if (id!=null) node = doc.getElementById(id);
  if (node==null) {
    node = myCreateElementSVG("path");
    node.setAttribute("id", id);
    svgpicture.appendChild(node);
  }
  node.setAttribute("d","M"+(p[0]*xunitlength+origin[0])+","+
    (height-p[1]*yunitlength-origin[1])+" "+
    (q[0]*xunitlength+origin[0])+","+(height-q[1]*yunitlength-origin[1]));
  node.setAttribute("stroke-width", strokewidth);
  node.setAttribute("stroke", stroke);
  node.setAttribute("fill", fill);
  if (marker!="none") {
    if (marker=="dot" || marker=="arrowdot")
      node.setAttribute("marker-start", "url(#dot)");
    node.setAttribute("marker-end", "url(#"+marker+")");
  }
//  if (!isIE) 
    if (marker=="dot" || marker=="arrowdot") {
      dot(p,4/xunitlength,markerstroke,markerfill);
      if (marker=="arrowdot") arrowhead(p,q);
      dot(q,4/xunitlength,markerstroke,markerfill);
    } else if (marker=="arrow") arrowhead(p,q);
}

function path(plist,id,c) {
  if (c==null) c="";
  var node;
  if (id!=null) node = doc.getElementById(id);
  if (node==null) {
    node = myCreateElementSVG("path");
    node.setAttribute("id", id);
    svgpicture.appendChild(node);
  }
  if (typeof plist == "string") var st = plist;
  else {
    var st = "M";
    st += (plist[0][0]*xunitlength+origin[0])+","+
          (height-plist[0][1]*yunitlength-origin[1])+" "+c;
    for (var i=1; i<plist.length; i++)
      st += (plist[i][0]*xunitlength+origin[0])+","+
            (height-plist[i][1]*yunitlength-origin[1])+" ";
  }
  node.setAttribute("d", st);
  node.setAttribute("stroke-width", strokewidth);
  node.setAttribute("stroke", stroke);
  node.setAttribute("fill", fill);
  if (marker!="none") {
    if (marker=="dot" || marker=="arrowdot")
      node.setAttribute("marker-start", "url(#dot)");
    node.setAttribute("marker-mid", "url(#"+marker+")");
    node.setAttribute("marker-end", "url(#"+marker+")");
  }
  if (/*!isIE &&*/ (marker=="dot" || marker=="arrowdot"))
    for (var i=0; i<plist.length; i++)
      if (c!="C" || i!=1 && i!=2)
        dot(plist[i],4/xunitlength,markerstroke,markerfill);
}

function curve(plist,id) {
  path(plist,id,"T");
}

function circle(center,radius,id) { // coordinates in units
  var node;
  if (id!=null) node = doc.getElementById(id);
  if (node==null) {
    node = myCreateElementSVG("circle");
    node.setAttribute("id", id);
    svgpicture.appendChild(node);
  }
  node.setAttribute("cx",center[0]*xunitlength+origin[0]);
  node.setAttribute("cy",height-center[1]*yunitlength-origin[1]);
  node.setAttribute("r",radius*xunitlength);
  node.setAttribute("stroke-width", strokewidth);
  node.setAttribute("stroke", stroke);
  node.setAttribute("fill", fill);
}

function ellipse(center,rx,ry,id) { // coordinates in units
  var node;
  if (id!=null) node = doc.getElementById(id);
  if (node==null) {
    node = myCreateElementSVG("ellipse");
    node.setAttribute("id", id);
    svgpicture.appendChild(node);
  }
  node.setAttribute("cx",center[0]*xunitlength+origin[0]);
  node.setAttribute("cy",height-center[1]*yunitlength-origin[1]);
  node.setAttribute("rx",rx*xunitlength);
  node.setAttribute("ry",ry*yunitlength);
  node.setAttribute("stroke-width", strokewidth);
  node.setAttribute("stroke", stroke);
  node.setAttribute("fill", fill);
}

function rect(p,q,id,rx,ry) { // opposite corners in units, rounded by radii
  var node;
  if (id!=null) node = doc.getElementById(id);
  if (node==null) {
    node = myCreateElementSVG("rect");
    node.setAttribute("id", id);
    svgpicture.appendChild(node);
  }
  node.setAttribute("x",p[0]*xunitlength+origin[0]);
  node.setAttribute("y",height-q[1]*yunitlength-origin[1]);
  node.setAttribute("width",(q[0]-p[0])*xunitlength);
  node.setAttribute("height",(q[1]-p[1])*yunitlength);
  if (rx!=null) node.setAttribute("rx",rx*xunitlength);
  if (ry!=null) node.setAttribute("ry",ry*yunitlength);
  node.setAttribute("stroke-width", strokewidth);
  node.setAttribute("stroke", stroke);
  node.setAttribute("fill", fill);
}

function text(p,st,pos,id) {
  var textanchor = "middle";
  var dx = 0; var dy = 5;
  if (pos!=null) {
    if (pos.slice(0,5)=="above") dy = -10;
    if (pos.slice(0,5)=="below") dy = 20;
    if (pos.slice(0,5)=="right" || pos.slice(5,10)=="right") {
      textanchor = "start";
      dx = 8;
    }
    if (pos.slice(0,4)=="left" || pos.slice(5,9)=="left") {
      textanchor = "end";
      dx = -8;
    }
  }
  var node;
  if (id!=null) node = doc.getElementById(id);
  if (node==null) {
    node = myCreateElementSVG("text");
    node.setAttribute("id", id);
    svgpicture.appendChild(node);
    node.appendChild(doc.createTextNode(st));
  }
  node.setAttribute("x",p[0]*xunitlength+origin[0]+dx);
  node.setAttribute("y",height-p[1]*yunitlength-origin[1]+dy);
  node.setAttribute("font-style",fontstyle);
  node.setAttribute("font-family",fontfamily);
  node.setAttribute("font-size",fontsize);
  node.setAttribute("text-anchor",textanchor);
  return p;
}

function dot(center,radius,s,f) { // coordinates in units
  if (s==null) s = stroke; if (f==null) f = fill;
  var node = myCreateElementSVG("circle");
  node.setAttribute("cx",center[0]*xunitlength+origin[0]);
  node.setAttribute("cy",height-center[1]*yunitlength-origin[1]);
  node.setAttribute("r",radius*xunitlength);
  node.setAttribute("stroke-width", strokewidth);
  node.setAttribute("stroke", s);
  node.setAttribute("fill", f);
  svgpicture.appendChild(node);
}

function arrowhead(p,q) { // draw arrowhead at q (in units)
  var v = [p[0]*xunitlength+origin[0],height-p[1]*yunitlength-origin[1]];
  var w = [q[0]*xunitlength+origin[0],height-q[1]*yunitlength-origin[1]];
  var u = [w[0]-v[0],w[1]-v[1]];
  var d = Math.sqrt(u[0]*u[0]+u[1]*u[1]);
  if (d > 0.00000001) {
    u = [u[0]/d, u[1]/d];
    up = [-u[1],u[0]];
    var node = myCreateElementSVG("path");
    node.setAttribute("d","M "+(w[0]-15*u[0]-4*up[0])+" "+
      (w[1]-15*u[1]-4*up[1])+" L "+(w[0]-3*u[0])+" "+(w[1]-3*u[1])+" L "+
      (w[0]-15*u[0]+4*up[0])+" "+(w[1]-15*u[1]+4*up[1])+" z");
    node.setAttribute("stroke-width", markerstrokewidth);
    node.setAttribute("stroke", markerstroke);
    node.setAttribute("fill", arrowfill);
    svgpicture.appendChild(node);    
  }
}

function axes() {
  var pnode = myCreateElementSVG("path");
  var st="M0,"+(height-origin[1])+" "+width+","+
    (height-origin[1])+" M"+origin[0]+",0 "+origin[0]+","+height;
  for (var x = origin[0]+xunitlength; x<width; x = x+xunitlength)
    st += " M"+x+","+(height-origin[1]+3)+" "+x+","+(height-origin[1]-3);
  for (var x = origin[0]-xunitlength; x>0; x = x-xunitlength)
    st += " M"+x+","+(height-origin[1]+3)+" "+x+","+(height-origin[1]-3);
  for (var y = height-origin[1]+yunitlength; y<height; y = y+yunitlength)
    st += " M"+(origin[0]+3)+","+y+" "+(origin[0]-3)+","+y;
  for (var y = height-origin[1]-yunitlength; y>0; y = y-yunitlength)
    st += " M"+(origin[0]+3)+","+y+" "+(origin[0]-3)+","+y;
  pnode.setAttribute("d",st);
  pnode.setAttribute("stroke-width", .5);
  pnode.setAttribute("stroke", axesstroke);
  pnode.setAttribute("fill", fill);
  svgpicture.appendChild(pnode);
}

