// This is an adapted version of the javascript to make the code work within
// the context of my website. It is more than 661 bytes.
//
// the original code is at http://www.paulhammond.org/2010/08/1k/original.js
// the compressed code is at http://www.paulhammond.org/2010/08/1k/compressed.js
// and you can see it in action at http://www.paulhammond.org/2010/08/1k/entry/
// more info at http://www.paulhammond.org/2010/08/1k/

// Changes:
// 1. this:
if(!!document.createElement('canvas').getContext){
$(document).ready(function(){
  inserted = $('#p-2010-08-1k p:eq(3)').before('<p id="p-2010-08-1k-demo"><canvas></p>');
  var innerWidth=490;
  var innerHeight=210;

// 2. b is now a div, not the body element
// 3. hardcode the height and width of the canvas and div elements
// 4. some different styles on canvas and div
// 5. consider offset when calculating the click target

// lookup:
// a   = 10
// b   = body
// c   = canvas
// d   = document
// e   = event
// f() = floor(x/10)
// g   = grid
// i   = iterator
// j   = iterator
// h   = height of grid (g[1].length)
// n   = "nodes" - array of [x,y,v]
// o   = e.pageX (used in c.onclick)
// r() = rectangle()
// t   = canvas.context
// w   = width of grid (g.length)
// z() = zoom!()

// to compress:
// perl -p -0 -e 's!(//[^\n]*)?\n\s*!!g;s!;}!}!g;s!;+!;!g' <script.js >compressed.js

function f(i){
  return (i-i%a)/a
}

function r(x,y,i){
  t.fillStyle='#'+i;
  t.fillRect(x*a+1,y*a+1,9,9);
}

var g=[],n=[],a=10,i,j,h=f(innerHeight-a),w=f(innerWidth),b=$('#p-2010-08-1k-demo').get(0),c=b.children[0],t=c.getContext('2d');

$(b).width(10*w);
c.style.display='block';b.style.padding='0 1px 1px 0';b.style.background='#333333';
c.width=a*w;c.height=a*h;

for(i=w;i-->0;){
  g[i]=[];
  for(j=h;j-->0;){
    g[i][j]=-1;
    r(i,j,'444')
  }
}

// G = this grid square
// N = this node info [x,y,dx,dy]
// x = y
// y = y
// v = direction ("velocity")

function z(){
  for(i=n.length;i-->0;){
    var N=n[i],x=N[0],y=N[1],v=N[2],G=g[x][y];
    r(x,y,G>0?'fff':'000');
    g[x][y]*=-1;
    x+=G*(1-v)%2;
    y+=G*(2-v)%2;
    v+=G;
    x=x<0?w-1:x%w;
    y=y<0?h-1:y%h;
    v=v<0?3:v%4;
    n[i]=[x,y,v];
    r(x,y,'fc0');
  }
  setTimeout(z,100);
}

c.onclick=function(e){
  x=f(e.pageX-$(c).offset().left);
  if(x<w&&n.push([x,f(e.pageY-$(c).offset().top),1])&&!n[1])z()
}

})};

