/*
 *
Copyright (c) 2008, R. Alexander Milowski <alex@milowski.com>
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 - Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.
 - Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.
 - Neither the name of the R. Alexander Milowski nor the names of its contributors
   may be used to endorse or promote products derived from this software
   without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

 *
 */

var Graph2DFactory = {
   objs: {},
   graphs: {},
   attach: function(id,functions) {
      var g =  new Graph2D(id);
      g.functions = functions;
      return g;
   },
   create: function(id) {
      return new Graph2D(id);
   },
   makeFunction: function(expression) {
      var id = (new Date()).getTime();
      script = document.createElement("script");
      script.setAttribute("type","text/javascript");
      script.appendChild(document.createTextNode("Graph2DFactory.objs["+id+"] = function(x) { return "+expression+"};"));
      document.body.appendChild(script);
      var func = this.objs[id];
      delete this.objs[id];
      document.body.removeChild(script);
      return func;
   },
   createFromDiv: function(div) {
      var current = div.firstChild;
      var canvas = null;
      var controls = null;
      var functions = [];
      while (current) {
         if (current.tagName && current.tagName.toLowerCase()=="div" && current.className.indexOf("function")>=0) {
            //alert("Adding: "+current.textContent);
            var exp = document.createRange();
            exp.selectNode(current);
            functions.push({ element: current, exp: this.makeFunction(exp.toString()) });
            current.style.display = "none";
         } else if (current.tagName && current.tagName.toLowerCase()=="div" && current.className.indexOf("controls")>=0) {
            controls = current;
         } else if (current.tagName && current.tagName.toLowerCase()=="canvas") {
            canvas = current;
         }
         current = current.nextSibling;
      }
      var graph = null;
      if (canvas) {
         graph = this.create(canvas);
         var id = div.getAttribute("id");
         if (id) {
            this.graphs[id] = graph;
            graph.id = id;
         }
         for (var i=0; i<functions.length; i++) {
            var id = functions[i].element.getAttribute("id");
            var options = {};
            options.color = functions[i].element.style.color;
            graph.addFunction(id ? id : "f"+i,functions[i].exp,options);
         }
         graph.draw();
      }
      if (controls) {
         current = controls.firstChild;
         while (current) { 
            if (current.className) {
               var name = current.className.toLowerCase();
               if (name=='zoom') {
                  var zoomIn = document.createElement("button");
                  current.appendChild(zoomIn);
                  zoomIn.appendChild(document.createTextNode("+"));
                  zoomIn.onclick = function() {
                     graph.scale += 10;
                     graph.clear();
                     graph.draw();
                  };
                  var zoomOut = document.createElement("button");
                  current.appendChild(zoomOut);
                  zoomOut.appendChild(document.createTextNode("-"));
                  zoomOut.onclick = function() {
                     if (graph.scale<=10) {
                        return;
                     }
                     graph.scale -= 10;
                     graph.clear();
                     graph.draw();
                  };
               } else if (name=='pan') {
               } else if (name=='reset') {
                  var redraw = document.createElement("button");
                  current.appendChild(redraw);
                  redraw.appendChild(document.createTextNode("Reset"));
                  redraw.onclick = function() {
                     graph.restore();
                     graph.clear();
                     graph.draw();
                  };
               } else if (name=='redraw') {
                  var redraw = document.createElement("button");
                  current.appendChild(redraw);
                  redraw.appendChild(document.createTextNode("Redraw"));
                  redraw.onclick = function() {
                     graph.clear();
                     graph.draw();
                  };
               }
            }
            current = current.nextSibling;
         }
      }
   },
   detect: function(start) {
      try {
      var current = start ? start : document.body.firstChild;
      while (current!=document.body) {
         //alert(current.tagName+" "+current.firstChild+" "+current.nextSibling);
         var descend = true;
         if (current.tagName && current.tagName.toLowerCase()=="div" && current.className.indexOf("graph2d")>=0) {
            Graph2DFactory.createFromDiv(current);
            descend = false;
         } 
         if (descend && current.firstChild) {
            current = current.firstChild;
         } else if (current.nextSibling) {
            current = current.nextSibling;
         } else {
            while (current!=document.body && !current.nextSibling) {
               current = current.parentNode;
            }
            if (current!=document.body) {
               current = current.nextSibling;
            }
         }
      } 
      } catch (ex) {
         alert(ex);
      }
   }
};   

function Graph2D(idOrElement) {
   if (typeof idOrElement == "string") {
      this.id = idOrElement;
      this.canvas = document.getElementById(idOrElement);
   } else {
      this.canvas = idOrElement;
   }

   var current = this;
   this.canvas.addEventListener('mousedown',function(event) {
      current.mouseStart = [ event.clientX, event.clientY ];
      current.canvas.style.cursor = "move";
   },true);
   this.canvas.addEventListener('mouseup',function(event) {
      if (!current.mouseStart) {
         return;
      }
      var dx = event.clientX - current.mouseStart[0];
      var dy = event.clientY - current.mouseStart[1];
      if (dx==0 && dy==0) {
         var now = (new Date()).getTime();
         if (current.firstClick && (now-current.firstClick.timestamp)<1501) {
            dx = event.clientX - current.firstClick.x;
            dy = event.clientY - current.firstClick.y
            current.firstClick = null;
         } else {
            current.firstClick = {
               x: event.clientX,
               y: event.clientY,
               timestamp: now
            };
            return;
         }
      } else {
         current.firstClick = null;
      }
      current.canvas.style.cursor = "default";
      current.position[0] = current._coordinateX(current._translateX(current.position[0])-dx);
      current.position[1] = current._coordinateY(current._translateY(current.position[1])+dy);
      current.mouseStart = null;
      current.clear();
      current.draw();
   },true);
   if (this.canvas.getContext){
      this.ctx = this.canvas.getContext('2d');
   }
   this.grid = [ parseInt(this.canvas.getAttribute("width")),
                 parseInt(this.canvas.getAttribute("height")) ];
   this.origin = [ this.grid[0]/2, this.grid[1]/2 ];
   this.position = [ 0, 0 ];
   this.scale = 50;
   this.axisColor = [255,0,0];
   this.graphColor = [0,0,0];
   this.save();
   this.functions  = {}
   this.drawn = false;
}

Graph2D.prototype.save = function() {
   this.saved = {
       position: [ this.position[0], this.position[1] ],
       origin: [ this.origin[0], this.origin[1] ],
       scale: this.scale
   };
}

Graph2D.prototype.restore = function() {
   this.position = [ this.saved.position[0], this.saved.position[1] ];
   this.origin = [ this.saved.origin[0], this.saved.origin[1] ];
   this.scale = this.saved.scale;
}

Graph2D.prototype.addFunction = function(fname,f,options) {
   var fdef = {
      name: fname,
      f: f
   };
   if (options) {
      for (var name in options) {
         fdef[name] = options[name];
      }
   }
   this.functions[fname] = fdef;
   return fdef;
}

Graph2D.prototype.resize = function(width,height) {
   this.grid = [ width, height];
   this.origin = [ this.grid[0]/2, this.grid[1]/2 ];
   this.canvas.setAttribute("width",width);
   this.canvas.setAttribute("height",height);
}

Graph2D.prototype._translateX = function(x) {
   return (x-this.position[0])*this.scale+this.origin[0];
}

Graph2D.prototype._translateY = function(y) {
   return this.origin[1]-(y+this.position[1])*this.scale;
}

Graph2D.prototype._coordinateX = function(xpos) {
   return (xpos-this.origin[0])/this.scale + this.position[0];
}

Graph2D.prototype._coordinateY = function(ypos) {
   return (this.origin[1]-ypos)/this.scale - this.position[1];
}

Graph2D.prototype._drawAxis = function() {
   // Set color & width;
   this.ctx.strokeStyle = "rgb("+this.axisColor[0]+","+this.axisColor[1]+","+this.axisColor[2]+")";
   this.ctx.lineWidth = 1;

   var height = this.scale/4;

   // Draw the origin lines
   var xpos = this._translateX(0);
   var ypos = this._translateY(0);

   this.ctx.font = "10px Arial, Sans-serif";

   // x axis
   if (ypos>=0 && ypos<this.grid[1]) {
      // Draw the markers on the x axis;
      var max = this._coordinateX(this.grid[0]);
      //alert(this._coordinateX(0)+" "+this._coordinateX(this.grid[0])+" "+max);
      for (var x=Math.floor(this._coordinateX(0)); x<max; x += 1 ) {
         if (x==0) {
            continue;
         }
         var tickX = this._translateX(x);
         //alert(x+" "+tickX);
         if (tickX>=0 && tickX<this.grid[0]) {
            this.ctx.beginPath();
            this.ctx.strokeStyle = "rgb(240,240,240)";
            this.ctx.moveTo(tickX,0);
            this.ctx.lineTo(tickX,this.grid[1]);
            this.ctx.stroke();
            this.ctx.strokeStyle = "rgb("+this.axisColor[0]+","+this.axisColor[1]+","+this.axisColor[2]+")";
            this.ctx.beginPath();
            this.ctx.moveTo(tickX,0);
            this.ctx.lineTo(tickX,height/2);
            if (this.ctx.fillText) {
               this.ctx.fillText(x+"",tickX+2,8);
            }
            this.ctx.moveTo(tickX,ypos+height);
            this.ctx.lineTo(tickX,ypos-height);
            this.ctx.moveTo(tickX,this.grid[1]-height/2);
            this.ctx.lineTo(tickX,this.grid[1]);
            this.ctx.stroke();
         }
      }
      this.ctx.moveTo(0,ypos);
      this.ctx.lineTo(this.grid[0],ypos);
      this.ctx.stroke();
   } else {
      var max = this._coordinateX(this.grid[0]);
      for (var x=Math.floor(this._coordinateX(0)); x<max; x += 1 ) {
         var tickX = this._translateX(x);
         if (tickX>=0 && tickX<this.grid[0]) {
            this.ctx.beginPath();
            this.ctx.strokeStyle = "rgb(240,240,240)";
            this.ctx.moveTo(tickX,0);
            this.ctx.lineTo(tickX,this.grid[1]);
            this.ctx.stroke();
            this.ctx.strokeStyle = "rgb("+this.axisColor[0]+","+this.axisColor[1]+","+this.axisColor[2]+")";
            this.ctx.beginPath();
            this.ctx.moveTo(tickX,0);
            this.ctx.lineTo(tickX,height/2);
            if (this.ctx.fillText) {
               this.ctx.fillText(x+"",tickX+2,8);
            }
            this.ctx.moveTo(tickX,this.grid[1]-height/2);
            this.ctx.lineTo(tickX,this.grid[1]);
            this.ctx.stroke();
         }
      }
      this.ctx.stroke();
   }

   // y axis
   if (xpos>=0 && xpos<this.grid[0]) {
      // Draw the markers on the y axis;
      var max = this._coordinateY(0);
      //alert(this._coordinateY(0)+" "+this._coordinateY(this.grid[1])+" "+max);
      for (var y=Math.floor(this._coordinateY(this.grid[1])); y<max; y += 1 ) {
         if (y==0) {
            continue;
         }
         var tickY = this._translateY(y);
         //alert(y+" "+tickY);
         if (tickY>=0 && tickY<this.grid[1]) {
            this.ctx.beginPath();
            this.ctx.strokeStyle = "rgb(240,240,240)";
            this.ctx.moveTo(0,tickY);
            this.ctx.lineTo(this.grid[0],tickY);
            this.ctx.stroke();
            this.ctx.strokeStyle = "rgb("+this.axisColor[0]+","+this.axisColor[1]+","+this.axisColor[2]+")";
            this.ctx.beginPath();
            this.ctx.moveTo(0,tickY);
            this.ctx.lineTo(height/2,tickY);
            if (this.ctx.fillText) {
               this.ctx.fillText(y+"",2,tickY+10);
            }
            this.ctx.moveTo(xpos+height,tickY);
            this.ctx.lineTo(xpos-height,tickY);
            this.ctx.moveTo(this.grid[0]-height/2,tickY);
            this.ctx.lineTo(this.grid[0],tickY);
            this.ctx.stroke();
         }
      }
      this.ctx.moveTo(xpos,0);
      this.ctx.lineTo(xpos,this.grid[1]);
      this.ctx.stroke();
   } else {
      this.ctx.beginPath();
      var max = this._coordinateY(0);
      for (var y=Math.floor(this._coordinateY(this.grid[1])); y<max; y += 1 ) {
         var tickY = this._translateY(y);
         if (tickY>=0 && tickY<this.grid[1]) {
            this.ctx.beginPath();
            this.ctx.strokeStyle = "rgb(240,240,240)";
            this.ctx.moveTo(0,tickY);
            this.ctx.lineTo(this.grid[0],tickY);
            this.ctx.stroke();
            this.ctx.strokeStyle = "rgb("+this.axisColor[0]+","+this.axisColor[1]+","+this.axisColor[2]+")";
            this.ctx.beginPath();
            this.ctx.moveTo(0,tickY);
            this.ctx.lineTo(height/2,tickY);
            if (this.ctx.fillText) {
               this.ctx.fillText(y+"",2,tickY+10);
            }
            this.ctx.moveTo(this.grid[0]-height/2,tickY);
            this.ctx.lineTo(this.grid[0],tickY);
            this.ctx.stroke();
         }
      }
      this.ctx.stroke();
   }

}

Graph2D.prototype.clear = function() {
   if (!this.canvas.getContext) {
      return;
   }
   this.ctx.clearRect(0,0,this.grid[0],this.grid[1]);
   this.drawn = false;
}
Graph2D.prototype.draw = function() {
   if (this.onBeforeDraw) {
      this.onBeforeDraw();
   }
   if (!this.canvas.getContext) {
      return;
   }
   if (!this.drawn) {
      this.ctx.clearRect(0,0,this.grid[0],this.grid[1]);
      this._drawAxis();
   }
   for (var name in this.functions) {
      var fdef = this.functions[name];
      var color = this.graphColor;
      if (fdef.color) {
         color = fdef.color;
      }
      var f = fdef.f;
      this.ctx.strokeStyle = typeof(color)=="object" ? "rgb("+color[0]+","+color[1]+","+color[2]+")" : color;
      this.ctx.beginPath();

      var onGrid = true;
      try {
         var ystart = this._translateY(f(this._coordinateX(0)));
         if (ystart<0 || ystart>this.grid[1]) {
            onGrid = false;
         } else {
            this.ctx.moveTo(0,ystart);
         }
      } catch (e) {
         onGrid = false;
      }
      var xlimit = this.origin[0]/this.scale;
      var xinc = 1/this.scale;
      var ylast = null;
         
      for (var xpos=0; xpos<=this.grid[0]; xpos++) {
         x = this._coordinateX(xpos);
         var y = f(x);
         var ypos = isFinite(y) ? this._translateY(y) : 0;

         if (isNaN(y) || !isFinite(y) || ypos<0 || ypos>this.grid[1]) {
            if (onGrid) {
               if (isNaN(y)) {
               } else if (!isFinite(y)) {
                  if (y<0) {
                     this.ctx.lineTo(xpos,this.grid[1]);
                  } else {
                     this.ctx.lineTo(xpos,0);
                  }
               } else if (ypos>this.grid[1]) {
                  // closer to bottom
                  
                  if (((y>0 && ylast<0) || (y<0 && ylast>0)) && (Math.abs(y)+Math.abs(ylast))>10) {
                     this.ctx.lineTo(xpos,y>0 ? this.grid[1] : 0);
                  } else {
                     this.ctx.lineTo(xpos,this.grid[1]);
                  }
               } else {
                  if (((y>0 && ylast<0) || (y<0 && ylast>0)) && (Math.abs(y)+Math.abs(ylast))>10) {
                     this.ctx.lineTo(xpos,y>0 ? this.grid[1] : 0);
                  } else {
                     this.ctx.lineTo(xpos,0);
                  }
               }
            }
            onGrid = false;
         } else if (onGrid) {
            if ((y<0 && ylast>0) || (y>0 && ylast<0)) {
               var asymptote = false;
               if (xpos>0) {
                  var t = this._coordinateX(xpos - 1);
                  var t_f = f(t);
                  var lessThanZero = t_f<0;
                  //alert("Testing for asymptote between "+t+","+t_f+" and "+x+","+y+" lessThanZero="+lessThanZero);
                  for (t+=0.001; t<x; t += 0.001) {
                     var n = f(t);
                     if (lessThanZero && n>0 && Math.abs(n)>1) {
                        asymptote = true;
                     } else if (!lessThanZero && n<0 && Math.abs(n)>1) { 
                        asymptote = true;
                     }
                  }
               }
               if (asymptote) {
                  if (ylast>0) {
                     this.ctx.lineTo(xpos-1,0);
                  } else {
                     this.ctx.lineTo(xpos-1,this.grid[1]);
                  }
                  if (y>0) {
                     this.ctx.moveTo(xpos,0);
                  } else {
                     this.ctx.moveTo(xpos,this.grid[1]);
                  }
               } else {
                  this.ctx.lineTo(xpos,ypos);
               }
            } else {
               this.ctx.lineTo(xpos,ypos);
            }
         } else {
            onGrid = true;
            ylastPos = this._translateY(ylast);
            if ((y<0 && ylast>0) || (y>0 && ylast<0)) {
               // vertical asymptote
               if (y<0) {
                  // closer to bottom
                  this.ctx.moveTo(xpos-1,this.grid[1]-1);
               } else {
                  this.ctx.moveTo(xpos-1,0);
               }
            } else if ((ylastPos-this.grid[1])>0) {
               // closer to bottom
               this.ctx.moveTo(xpos-1,this.grid[1]-1);
            } else {
               this.ctx.moveTo(xpos-1,0);
            }
            this.ctx.lineTo(xpos,ypos);
         }
         ylast = y;
      }
      this.ctx.stroke();
   }
   this.drawn = true;
   if (this.onAfterDraw) {
      this.onAfterDraw();
   }
}

