var WIDTH = 400;
var HEIGHT = 400;
var RADIUS = 7;
var NUM_NODES = 9;

function draw_node(ctx, n) {
  ctx.save();

  ctx.beginPath();
  ctx.arc(n.x, n.y, RADIUS, 0, Math.PI*2, true);
  ctx.stroke();
  ctx.fill();

  ctx.restore();
}

function draw_edge(ctx, e) {
  //console.log("e: " + e.src.x + ", " + e.src.y + " : " + e.tgt.x + ", " + e.tgt.y);
  ctx.save();

  ctx.beginPath();
  ctx.moveTo(e.src.x, e.src.y);
  ctx.lineTo(e.tgt.x, e.tgt.y);
  ctx.stroke();

  ctx.restore();
}


function draw_graph(ctx, g) {
  ctx.lineWidth = 2;
//  ctx.strokeStyle = "#ffffff";
  ctx.strokeStyle = "#bbb";
  ctx.shadowBlur = 1.0;

  jQuery.each(g.edges, function(idx, e) {
    draw_edge(ctx, e);
  });

  //ctx.shadowBlur = 15.0;
  ctx.shadowColor = "rgba(255, 255, 255, 0.4)";
  ctx.shadowOffsetX = 0;
  ctx.shadowOffsetY = 0;

  ctx.lineWidth = 4;
  ctx.strokeStyle = "#30427d";
  ctx.fillStyle = "#ffffff";
//  ctx.fillStyle = "#30427d";

  jQuery.each(g.nodes, function(idx, n) {
    draw_node(ctx, n);
  });

}

function rand_int(max) {
  return(Math.round(Math.random() * max));
}

function random_node() {
  var padding = 2 * RADIUS;
  var x = rand_int(WIDTH - (2 * padding)) + padding;
  var y = rand_int(HEIGHT - (2 * padding)) + padding;
  return({x: x, y: y});
}

function distance(n1, n2) {
  return(Math.sqrt(Math.pow(n1.x - n2.x, 2) + Math.pow(n1.y - n2.y, 2)));
}

function collides(n1, n2) {
  var d = distance(n1, n2);
  //console.log("dist: " +  d + " : " + (d < (3 * RADIUS)));
  return(d < (3 * RADIUS));
} 

function choose(ary) {
  return(ary[Math.ceil(Math.random() * (ary.length - 1))]);
}

function make_graph(n_nodes) {
  var nodes = [];
  var edges = []
  var n;
  var c;

  for(var i = 0; i < n_nodes; i++) {
    do {
      n = random_node();
      c = false;
      jQuery.each(nodes, (function(idx, n2) { 
        if (collides(n, n2)) {
          c = true;
        }
      }));

      //console.log("i: " + i + ": " + c + " ==> len: " + nodes.length);
    } while (c);

    nodes.push(n);
  }

  var tgt;
  jQuery.each(nodes, (function(idx, src) {
    do {
      tgt = choose(nodes);
    } while((tgt.x == src.x) && (tgt.y == src.y));
    //console.log("new-tgt: " + tgt.x + ", " + tgt.y);

  edges.push({src: src, tgt: tgt});
  }));

  return({
    nodes: nodes,
    edges: edges
  });
}

function graph_header() {
  var ctx = $("#canvas")[0].getContext("2d");
  var g = make_graph(NUM_NODES);

  jQuery.each(g.nodes, function(idx, n) {
    //console.log("x: " + n.x + " y: " + n.y);
  });

  ctx.clearRect(0, 0, 300, 300);
  draw_graph(ctx, g);
}
