function cont() {
	g_running=true;
	Hide('run'); Hide('cont'); Show('stop');
	one_step();
}
function crash(x,y) {
	var w2=g_crash.width/2;
	g_ctx.drawImage(g_crash,x-w2,y-w2);
}
function crash_check() {
	if (g_x<=0) crash(0,g_y);
	if (g_y<=0) crash(g_x,0);
	if (g_x>=g_side) crash(g_side,g_y);
	if (g_y>=g_side) crash(g_x,g_side);
}
function fd() {
	g_ctx.beginPath(); ////
  g_ctx.moveTo(g_x,g_y);
  var dx=0; var dy=0;
  if (g_h==0) dy=-g_step;
  if (g_h==90) dx=g_step;
  if (g_h==180) dy=g_step;
  if (g_h==270) dx=-g_step;
  g_x=g_x+dx; g_y=g_y+dy;
  g_ctx.lineTo(g_x,g_y);
  g_ctx.stroke();
  ////crash_check();
}
function home() {
	g_ctx.clearRect(0,0,g_side,g_side);
	g_x=g_x0; g_y=g_y0; g_h=0;
}
function one_step() {
	if (g_running) {
		fd(); g_k++;
		if (g_k==g_numbers[g_j]) {
			g_j++; g_k=0; rt();
		}
		if (g_j==5) {
			g_i++; g_j=0
		}
		robot();
		if (g_i<4) {
			g_timer=setTimeout(one_step,200);
		} else {
			stop();
		}
	}
}
function resize() {
	var side=50*vmin();
  if (side!=g_side) setup();
}
function robot() {
	g_robot.clearRect(0,0,g_side,g_side);
	var i=g_h/90;
	var w2=g_img[0].width/2;
	g_robot.drawImage(g_img[i],g_x-w2,g_y-w2);
}
function rt() {
	g_h=g_h+90;
	if (g_h==360) g_h=0;
}
function run() {
	setup();
	Hide('run'); Hide('cont'); Show('stop');
	g_running=true;
	g_i=0; g_j=0; g_k=0;
	setTimeout(one_step,500);
}
function setup() {
	clearTimeout(g_timer);
	g_running=false;
	Hide('cont'); Hide('stop'); Show('run');
	g_side=50*vmin();
	var buttons=document.getElementById('buttons');
	buttons.style.width=g_side;
  var canvas=document.getElementById('c');
  canvas.width=g_side; canvas.height=g_side;
  g_ctx=canvas.getContext('2d');
	canvas=document.getElementById('robot');
	canvas.width=g_side; canvas.height=g_side;
  g_robot=canvas.getContext('2d');
  g_x0=g_side/2; g_y0=g_side*.75;
  g_step=g_side/8;
  home();
	setTimeout(robot,100)
}
function stop() {
	clearTimeout(g_timer);
	g_running=false;
	Hide('cont'); Hide('stop'); Show('run');
	if (g_i<4) Show('cont');
}
function vmin() {
  var w=innerWidth; var h=innerHeight;
  var v=w;
  if (h<w) v=h;
  return v/100;
}

function test() {
	g_i=0; g_j=0; g_k=0;
	one_step();
}
