// /tutorials/project_13/spiro.js
// globals
var g_side, g_step;
var g_ctx0, g_ctx1;
var g_x0, g_y0, g_x, g_y, g_h;
var g_n=28;
var g_numbers;
var g_k, g_ind
var g_img=[];
var g_rt;
var g_delay=1000;
var g_timer;
function arrow() {
  var w=g_side/10;
  var j=g_h/90;
  var w2=w/2;
  g_ctx1.clearRect(0,0,g_side,g_side);
  g_ctx1.drawImage(g_img[j],g_x-w2,g_y-w2,w,w);
}
function at_start() {
  return (g_x==g_x0 && g_y==g_y0 && g_h==0 && g_k==0 && g_rt==20);
}
function canvas_init() {
  var canvas = document.getElementById('c0');
  canvas.width=g_side; canvas.height=g_side;
  g_ctx0 = canvas.getContext('2d');
  g_ctx0.lineWidth=2;
  g_ctx0.lineCap='round';
  canvas = document.getElementById('c1');
  canvas.width=g_side; canvas.height=g_side;
  g_ctx1 = canvas.getContext('2d');
  home();
}
function dx_dy() {
  if (g_h==0) {g_dx=0; g_dy=-g_step;}
  if (g_h==90) {g_dx=g_step; g_dy=0;}
  if (g_h==180) {g_dx=0; g_dy=g_step;}
  if (g_h==270) {g_dx=-g_step; g_dy=0;}
}
function fd() {
  g_ctx0.beginPath();
  g_ctx0.moveTo(g_x, g_y);
  g_x += g_dx;
  g_y += g_dy;
  g_ctx0.lineTo(g_x, g_y);
  g_ctx0.stroke();
}
function home() {
  g_x=g_x0; g_y=g_y0; g_h=0; dx_dy();
}
function numbers() {
  g_ctx1.font='3vmin arial';
  var dx=g_ctx1.measureText('5');
  dx=Math.ceil(dx.width)+2;
  var x=g_side/30; var y=g_side/10;
  for (var i=0; i<5; i++) {
    g_ctx1.fillStyle='blue';
    if (i==g_ind) g_ctx1.fillStyle='red';
    g_ctx1.fillText(g_numbers[i],x,y);
    x+=dx;
  }
}
function one_step() {
  fd(); g_k++;
  if (g_k==g_numbers[g_ind]) {
    rt(); g_k=0; g_ind++;
    if (g_ind==5) g_ind=0;
  }
  if (!at_start()) {
    g_timer=setTimeout(one_step,g_delay);
  }
  arrow(); numbers();
}
function rt(n) {
  g_h+=90; g_h=g_h%360; dx_dy();
  g_rt++;
}
function run() {
  clearTimeout(g_timer);
  canvas_init();
  g_n++; g_n=g_n%g_patterns.length;
  g_numbers=g_patterns[g_n].split('');
  g_k=0; g_ind=0; g_rt=0;
  arrow(); numbers();
  setTimeout(one_step,2000);
}
function setup() {
  clearTimeout(g_timer);
  var wh=viewport();
  var w=wh.width; var h=wh.height;
  var s=Math.min(w,h);
  var s=parseInt(s/3);
  g_side=s; g_step=Math.round(s/8);
  g_x0=s/2; g_y0=s/2+2*g_step;
  canvas_init();
  setTimeout(arrow,1000);
}
function setup0(){
  for (var i=0;i<4; i++) {
    g_img[i]=new Image();
    g_img[i].src='images/'+i+'.png';
  }
  setup();
}
function viewport() {
  var doc = document, w = window;
  var docEl = (doc.compatMode && doc.compatMode === 'CSS1Compat')?
          doc.documentElement: doc.body;
  var width = docEl.clientWidth;
  var height = docEl.clientHeight;
  g_orientation='landscape';
  if (width<height) g_orientation='portrait';
  // mobile zoomed in?
  if ( w.innerWidth && width > w.innerWidth ) {
      width = w.innerWidth;
      height = w.innerHeight;
  }
  return {width: width, height: height};
}
