// Ink Drawing
//****************************************************************************//

function inkDrawerObject( canvasid, cmds, texid, lineWidth, offsetx, offsety, timeoutms ) {
  this.canvas = getObjectRef( canvasid );
  this.ctx = this.canvas.getContext('2d');
  this.pos = 0;
  this.cmds = cmds;
  this.timeoutms = timeoutms;
  
  setOpacity( this.canvas, 20 );
  
  // Set up environment
  this.ctx.lineWidth = lineWidth;
  this.ctx.lineCap = "round";
  this.ctx.strokeStyle = "#593002";
  /*
  if( window.excanvas ) {
    // excanvas doesn't support patterns
    this.ctx.strokeStyle = "#8e9295";
  }else{
    var imgptrn = getObjectRef( texid );
    var ptrn = this.ctx.createPattern(imgptrn,'repeat');
    this.ctx.strokeStyle = ptrn;
  }
  */
  this.ctx.clearRect(0,0,1000,1000 );
  this.ctx.translate( offsetx, offsety );
  this.ctx.save();

  this.draw = function() {
    if( this.pos >= this.cmds.length ) return;

    if( this.cmds.charAt(this.pos) == '(' ) {
      var j = this.pos+1;
      for(; this.cmds.charAt(j)!=')'; j++ );
      var loc = this.cmds.substring(this.pos+1,j);
      var coords = loc.split(',');
      this.drawpos( coords[0], coords[1] );
      this.pos = j;
    }
    var drew = false;
    while( !drew && this.pos < this.cmds.length ) {
      drew = this.drawcmd( this.cmds.charAt(this.pos) );
      this.pos++;
    }
    
    setTimeout( "inkdrawer.draw()", this.timeoutms );
  }
  
  this.drawpos = function( x, y ) {
    this.ctx.restore();
    this.ctx.save();
    this.ctx.translate( x, y);
  }
  
  this.drawcmd = function( cmd ) {
    if( cmd == '5' ) {
      // forward
      this.ctx.beginPath();
      this.ctx.moveTo(0,0 );
      this.ctx.lineTo(0,1);
      this.ctx.stroke();
      this.ctx.translate(0,1);
      return true;
    }else if( cmd == '8' ) {
      // forward 2
      this.ctx.beginPath();
      this.ctx.moveTo(0,0);
      this.ctx.lineTo(0,2);
      this.ctx.stroke();
      this.ctx.translate(0,2);
      return true;
    }else if( cmd == '0' ) {
      // forward without drawing
      this.ctx.translate(0,1);
      this.ctx.moveTo(0,0);
    }else if( cmd == '7' ) {
      // left 5.625 degrees
      this.ctx.rotate(-Math.PI/32);
    }else if( cmd == '9' ) {
      // right 5.625 degrees
      this.ctx.rotate(Math.PI/32);
    }else if( cmd == '4' ) {
      // left 11.25 degrees
      this.ctx.rotate(-Math.PI/16);
    }else if( cmd == '6' ) {
      // right 11.25 degrees
      this.ctx.rotate(Math.PI/16);
    }else if( cmd == '1' ) {
      // left 22.5 degrees
      this.ctx.rotate(-Math.PI/8);
    }else if( cmd == '3' ) {
      // right 22.5 degrees
      this.ctx.rotate(Math.PI/8);
    }else{
      return true;
    }
    return false;
  }

}