var G_BORDER_WIDTH = 10;  
var G_COLOURS = new Array('red', 'blue', 'yellow');
var G_COLOUR_ID = 0;
var G_TEXT_COUNT = 4;
var G_TEXT_FACTOR = 26*26*26*26;

function properties(obj) {
  var str = '';
  for (i in obj) {
	if (undefined != obj[i])
	{
	  str = str + i + ' = ' + obj[i] + '\n';
	}
  }
  return str;
} // properties

function str2num(str, n) {
  ///alert('str2num('+str.toString()+', '+n+')');
  var val = 0;
  var v;
  if (undefined == n) { n = -1; }
  // use an array to pass the parameter by reference
  while (str[0] && n) {
    v = str[0].charCodeAt(0);
    str[0] = str[0].substring(1);
    if ((v > 0x40 && v < 0x5B) || (v > 0x60 && v < 0x7B)) {
	  n--;
	  val = val * 26 + (v & 0x1F) - 1;
	}
  }
  return val;
} // str2num

function num2str(val, n) {
  var v;
  var str = '';
  while (val) {
	v = val % 26;
	val = (val - v) / 26;
	str = fromCharCode(v + 0x41) + str;
  }
  return str;
} // num2str

function addNode(x, y, w, h, c) {
  ///alert('addNode('+x+', '+y+', '+w+', '+h+', c)');
  var parent = document.getElementById('border');
  var element = document.createElement('div');
  
  element.innerHTML = '&nbsp;';	
  element.style.position = 'absolute';
  element.style.overflow = 'hidden';
  element.style.width  = w;
  element.style.height = h;
  //element.style.zIndex = 10;
  element.style.left = x;
  element.style.top  = y;
  element.style.backgroundColor = c;
  element.onclick = clicked;
  element.setAttribute('color', c.charAt(0));


  parent.appendChild(element); 
} // addNode

function split_horizontal(x, y, w, h, s) {
  var h1 =     s - G_BORDER_WIDTH /2; 
  var h2 = h - s - G_BORDER_WIDTH /2;
  var y1 = y;
  var y2 = y + h1 + G_BORDER_WIDTH;
  if (s < h/2) {
	return { x1: x, y1: y1, w1: w, h1: h1, 
			 x2: x, y2: y2, w2: w, h2: h2 } 
  } else {
	return { x1: x, y1: y2, w1: w, h1: h2, 
			 x2: x, y2: y1, w2: w, h2: h1 } 
  }
} // split_horizontal

function split_vertical(x, y, w, h, s) {
  var w1 =     s - G_BORDER_WIDTH /2; 
  var w2 = w - s - G_BORDER_WIDTH /2;
  var x1 = x;
  var x2 = x + w1 + G_BORDER_WIDTH;
  if (s < w/2) {
	return { x1: x1, y1: y, w1: w1, h1: h, 
			 x2: x2, y2: y, w2: w2, h2: h } 
  } else {
	return { x1: x2, y1: y, w1: w2, h1: h, 
			 x2: x1, y2: y, w2: w1, h2: h } 
  }
} // split_vertical

function split(object, sx, sy) {
  ///alert('canvasClicked('+object+', '+sx+', '+sy+')');

  var w = object.offsetWidth;
  var h = object.offsetHeight;

  if ((sx < G_BORDER_WIDTH) || (sx > w - G_BORDER_WIDTH) ||
	  (sy < G_BORDER_WIDTH) || (sy > h - G_BORDER_WIDTH)) {
	  // clicked to close to a border, don't do a thing, return this function immediately
	  return false;
  }

  var x = parseInt(object.style.left);
  var y = parseInt(object.style.top);

  var val;
/*

     \       /                 \       /
      +-----/-------------------\-----+
	  |\   /                     \   /|
	  | \ /                       \ / |
      |  x                         x  |
      | / \                       / \ |
      |/   \                     /   \|
      +-----\-------------------/-----+
     /       \                 /       \
    /         \               /         \
  y>x         y<h-x         y<x-w+h     y>w-x
                          y-h<x-w       y>w-x
									   

            / y-h>x-w
     +-----x
     |\   /|
     | \ / |
     |  x  |
     | / \ |
     |/   \|
	 /     \
    /|     |\
     |     |
     |     |/ 
     \     /
     |\   /|
     | \ / |
     |  x  |
     | / \ |
     |/   \|
     +-----x

*/
   

//  if (w < h) {
//  if (Math.abs(1 - sx / (w - sx)) < Math.abs(1 - sy / (h - sy))) {
//  if (Math.min(sx, w - sx) > Math.min(sy, h - sy)) {
   if ((sy < h-sx) && (sy > sx) || (sy > w-sx) && (sy-h < sx-w)) {
	val = split_horizontal(x, y, w, h, sy);
  } else {
	val = split_vertical(x, y, w, h, sx);
  }
  
  //alert('split(' + object + ' ' + x + ', ' + y + ')' + parseInt(object.style.left) + ', ' + h + ', ' + w + val);
  ///alert(properties(val));
  document.getElementById('border').removeChild(object);

  addNode(val['x1'], val['y1'], val['w1'], val['h1'], G_COLOURS[G_COLOUR_ID]);
  addNode(val['x2'], val['y2'], val['w2'], val['h2'], 'white');

  G_COLOUR_ID++;
  if (G_COLOUR_ID == G_COLOURS.length) { G_COLOUR_ID = 0; }

  return true;
} // split

function clicked(e) {

  // Get the target element
  var targ;
  if (!e) var e = window.event;
  if (e.target) targ = e.target;
  else if (e.srcElement) targ = e.srcElement;
  if (targ.nodeType == 3) { // defeat Safari bug
	  targ = targ.parentNode;
  }

  // Get the mouse position
  var posx = 0;
  var posy = 0;
  if (!e) var e = window.event;
  if (e.pageX || e.pageY) 	{
	  posx = e.pageX;
	  posy = e.pageY;
  }
  else if (e.clientX || e.clientY) 	{
	  posx = e.clientX + document.body.scrollLeft	+ document.documentElement.scrollLeft;
	  posy = e.clientY + document.body.scrollTop	+ document.documentElement.scrollTop;
  }
  // posx and posy contain the mouse position relative to the document

  // to the position in the element.
  var elem = targ;
  while(null != elem) {
	posx -= elem.offsetLeft;
	posy -= elem.offsetTop;
	elem = elem.offsetParent;
  }

  split(targ, posx, posy);

 
//    var div = document.createElement('div');

} // onClick

// Click on the full canvas
function canvasClicked(x, y) {
  ///alert('canvasClicked('+x+', '+y+')');
  var border = document.getElementById('border');
  var x1, x2, y1, y2
  var targ = false;

  // find the object
  for (i = 0; i < border.childNodes.length; i++) {
	x1 = parseInt(border.childNodes[i].style.left);
	y1 = parseInt(border.childNodes[i].style.top);
	x2 = parseInt(border.childNodes[i].style.width) + x1;
	y2 = parseInt(border.childNodes[i].style.height) + y1;
	///alert(x1+', '+y1+', '+x2+', '+y2);
	if ((x1 < x) && (x < x2) && (y1 < y) && (y < y2)) {
	  targ = border.childNodes[i];
	  x = x - x1;
	  y = y - y1;
	  break;
	}
  } // loop over the childs
  if (targ) {
    return split(targ, x, y);
  } 
  return false;
} // canvasClicked

function stringClicked(str) {
  var x, y;
  // convert to array (arguments must be passed by reference)
  var s = new Array(str);

  var border = document.getElementById('border');
  var fx = parseInt(border.style.width)  / G_TEXT_FACTOR;
  var fy = parseInt(border.style.height) / G_TEXT_FACTOR;
  
  while (s[0]) {
	x = str2num(s, G_TEXT_COUNT) * fx;
	y = str2num(s, G_TEXT_COUNT) * fx;
	if (s[0]) {
	  canvasClicked(x, y);
	}
  }
} // stringClick

function randomClicked() {
  var border = document.getElementById('border');
  var i = 43;
  while (i && !canvasClicked(
	  Math.random() * parseInt(border.style.width),
	  Math.random() * parseInt(border.style.height))) {
	// countdown to prevent endless loop
	i--;
  }
} // randomClicked

function setBorder(b) {
  // Make sure the size is even;
  G_BORDER_WIDTH = Math.round(b/2) *2;
} // setBorder

function blocks() {
  var border = document.getElementById('border');
  var str = '';
  for (i = 0; i < border.childNodes.length; i++) {
	str = str +
	  parseInt(border.childNodes[i].style.left) + 'x' +
	  parseInt(border.childNodes[i].style.top) + 'x' +
	  parseInt(border.childNodes[i].style.width) + 'x' +
	  parseInt(border.childNodes[i].style.height) + 'x' +
	  border.childNodes[i].getAttribute('color') + '_';
  }
  str = str + 
	parseInt(border.style.width) + 'x' +
	parseInt(border.style.height) + 'x' +
	G_BORDER_WIDTH;

  return str;
} blocks;

function clearCanvas() {
  ///alert('clear()');
  var border = document.getElementById('border');
  
  // Remove the old nodes
  while (border.firstChild) {
	border.removeChild(border.firstChild);
  }

  addNode(
	G_BORDER_WIDTH, G_BORDER_WIDTH, 
	border.offsetWidth  - 2 * G_BORDER_WIDTH, 
	border.offsetHeight - 2 * G_BORDER_WIDTH,
	'white');
} // clearCanvas

function saveCanvas() {
  top.location.href = 'http://mondriaan.technetium.be/?blk='+blocks();
  if (window.external) {
    window.external.AddFavorite(location.href, document.title);  }
} // saveCanvas
