/* 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.2 June 13, 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.*/

var xunitlength = 20;  // pixels
var yunitlength = 20;  // pixels
var origin = [0,0];   // in pixels (default is bottom left corner)
var border = 25;
var strokewidth = "1" // pixel
var stroke = "black"; // default line color
var fill = "none";    // default fill color
var fontstyle = "italic"; // default shape for text labels
var fontfamily = "times"; // default font
var fontsize = "20";      // default size
var markerstrokewidth = "1";
var markerstroke = "black";
var markerfill = "yellow";
var marker = "none";
var arrowfill = stroke;
var axesstroke = "black";
var pointerpos = null;
var coordinates = null;
var above = "above";
var below = "below";
var left = "left";
var right = "right";
var aboveleft = "aboveleft";
var aboveright = "aboveright";
var belowleft = "belowleft";
var belowright = "belowright";
var xMin=-5;
var xMax=5;
var yMin=-5;
var yMax=5;
var isIE = document.createElementNS==null;
var picture, svgpicture, doc, width, height, a, b, c, d, i, n, p, t, x, y;

function less(x,y) { return x < y }  // used for scripts in XML files
                                     // since IE does not handle CDATA well
function setText(st,id) { 
  var node = document.getElementById(id);
  if (node!=null)
    if (node.childNodes.length!=0) node.childNodes[0].nodeValue = st;
    else node.appendChild(document.createTextNode(st));
}

function plot(fun,xmin,xmax,points,id) {
  var p = [];
  var name = null;
  if (typeof xmin=="string") { name = xmin; xmin = xMin }
  else name = id;
  var min = (xmin==null?xMin:xmin);
  var max = (xmax==null?xMax:xmax);
  var inc = (points==null?(max-min)/100:(max-min)/points);
  for (var x = min; x < max+.0000001; x += inc)
    p[p.length] = [x, fun(x)];
  path(p,name)
}

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];
}

function drawPictures() {
  var src, id, dsvg, onmov;
  var pictures = document.getElementsByTagName("embed");
  var len = pictures.length;
  for (var index = 0; index < len; index++) {
    picture = (isIE ? pictures[index] : pictures[0]);
    src = picture.getAttribute("script");
//    eval(src.replace(/\s\s/g,";")); //for XML version
    id = picture.getAttribute("id");
    dsvg = picture.getAttribute("src");
    onmov = picture.getAttribute("onmousemove");
    if (id == null || id == "") {
      id = "picture"+(index+1);
      picture.setAttribute("id",id);
    }
    eval(src);
    if (isIE) src = src.replace(/([^\r])\n/g,"$1\r");
    setText("<embed width=\""+width+"\" height=\""+height+"\" src=\""+
            dsvg+"\" "+(onmov!=null?"onmousemove=\""+onmov+"\"":"")+
            (isIE?"\r":"\n")+"script=\'"+src+"\'>",id+"script");
//    setText(src.replace(/\s\s/g,"\r"),id+"script"); //for XML version
  }
}

function initPicture(xmin,xmax,ymin,ymax) {
  strokewidth = "1"; // pixel
  stroke = "black"; // default line color
  fill = "none";    // default fill color
  marker = "none";
  xMin = xmin;
  xMax = xmax;
  yMin = ymin;
  yMax = ymax;
  width = picture.getAttribute("width");
  height = picture.getAttribute("height");
  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) {
      svgpicture = picture.getSVGDocument().getElementById("root");
      doc = picture.getSVGDocument();
    } else {
      var qnode = document.createElementNS("http://www.w3.org/2000/svg","svg");
      qnode.setAttribute("id",picture.getAttribute("id"));
      qnode.setAttribute("width",picture.getAttribute("width"));
      qnode.setAttribute("height",picture.getAttribute("height"));
      picture.parentNode.replaceChild(qnode,picture);
      svgpicture = qnode;
      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);
  }
}

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=="dot" || marker=="arrowdot") {
    dot(p,4,markerstroke,markerfill);
    if (marker=="arrowdot") arrowhead(p,q);
    dot(q,4,markerstroke,markerfill);
  } else if (marker=="arrow") arrowhead(p,q);
}

function path(plist,id,c) {
  if (c==null) c="";
  var node, st, i;
  if (id!=null) node = doc.getElementById(id);
  if (node==null) {
    node = myCreateElementSVG("path");
    node.setAttribute("id", id);
    svgpicture.appendChild(node);
  }
  if (typeof plist == "string") st = plist;
  else {
    st = "M";
    st += (plist[0][0]*xunitlength+origin[0])+","+
          (height-plist[0][1]*yunitlength-origin[1])+" "+c;
    for (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=="dot" || marker=="arrowdot")
    for (i=0; i<plist.length; i++)
      if (c!="C" || i!=1 && i!=2)
        dot(plist[i],4,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 arc(start,end,radius,id) { // 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"+(start[0]*xunitlength+origin[0])+","+
    (height-start[1]*yunitlength-origin[1])+" A"+radius*xunitlength+","+
     radius*xunitlength+" 0 0,0 "+(end[0]*xunitlength+origin[0])+","+
    (height-end[1]*yunitlength-origin[1]));
  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.lastChild.nodeValue = 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);
  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 x, y, pnode, st;
  pnode = myCreateElementSVG("path");
  st="M0,"+(height-origin[1])+" "+width+","+
    (height-origin[1])+" M"+origin[0]+",0 "+origin[0]+","+height;
  for (x = origin[0]+xunitlength; x<width; x = x+xunitlength)
    st += " M"+x+","+(height-origin[1]+3)+" "+x+","+(height-origin[1]-3);
  for (x = origin[0]-xunitlength; x>0; x = x-xunitlength)
    st += " M"+x+","+(height-origin[1]+3)+" "+x+","+(height-origin[1]-3);
  for (y = height-origin[1]+yunitlength; y<height; y = y+yunitlength)
    st += " M"+(origin[0]+3)+","+y+" "+(origin[0]-3)+","+y;
  for (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);
}

