window.onload = addbutton;

var number = 0;
var current = 0;

var targettop = new Array();
var targetleft = new Array();
targettop[0] = 0;
targetleft[0] = 0;

function chgcolor() {

  var color='#';
  for(var index = 0; index < 6; index++) {

    var hexnum = Math.floor(Math.random()*16);
    color += hexnum.toString(16);

  }

  document.getElementById('buttongame').style.backgroundColor = color;

}

function chgbutton() {

  document.getElementById('button'+current).value = "Don't click me!";
  current = Math.floor(Math.random()*number);
  document.getElementById('button'+current).value = "Click me please!";

}

function move() {

  for(var count = 0; count < number; count++) {

    var divtop = document.getElementById('div'+count).style.top;
    var divleft = document.getElementById('div'+count).style.left;

    // get rid of "px", convert to number
    divtop = eval(divtop.substring(0, divtop.length - 2));
    divleft = eval(divleft.substring(0, divleft.length - 2));

    var height = document.getElementById('buttongame').clientHeight;
    var width = document.getElementById('buttongame').clientWidth;

    if(targettop[count] > divtop) divtop += 20;
    if(targettop[count] < divtop) divtop -= 20;
    if(targetleft[count] > divleft) divleft += 20;
    if(targetleft[count] < divleft) divleft -= 20;

    if(targettop[count] == divtop && targetleft[count] == divleft) {

      targettop[count] = 20*Math.floor(Math.random()*Math.floor(height/20 - 1));
      targetleft[count] = 20*Math.floor(Math.random()*Math.floor(width/20 - 7));

    }

    document.getElementById('div'+count).style.top = divtop + 'px';
    document.getElementById('div'+count).style.left = divleft + 'px';

  }

  chgcolor();
  chgbutton();
  setTimeout("move()",500);

}

function handleButtonClick(event) {

  if (!event)
      event = window.event;
  var elem = event.target ? event.target : event.srcElement;

  var button = elem.id.substring(6,elem.id.length);

  if(button == current) {
    addbutton();
  } else {
    alert('No!  Not that button!');
  }

}

function addbutton() {

  var newdiv = document.createElement("div");
  newdiv.id = 'div' + number;
  newdiv.style.top = '0px';
  newdiv.style.left = '0px';
  newdiv.style.position = 'absolute';
  targettop[number] = 0;
  targetleft[number] = 0;

  var newbutton = document.createElement("input");
  newbutton.type = 'button';
  newbutton.id = 'button' + number;
  newbutton.value = "Don't Click Me!";
  if (newbutton.addEventListener) {
    newbutton.addEventListener('click',handleButtonClick,false);
  } else if (newbutton.attachEvent) {
    newbutton.attachEvent('onclick',handleButtonClick);
  } else {
    newbutton.onclick = handleButtonClick;
  }

  newdiv.appendChild(newbutton);
  document.getElementById('buttongame').appendChild(newdiv);

  number++;
  setTimeout("move()",250);

}
