function $(name) {
  return window.document.getElementById(name);
}

function windowHeight() {
  if (typeof(window.innerHeight) == 'number')
    return window.innerHeight;
  else if (document.documentElement && document.documentElement.clientHeight)
    return document.documentElement.clientHeight;
  else
    return document.body.clientHeight;
}

function windowWidth() {
  if (typeof(window.innerWidth) == 'number')
    return window.innerWidth;
  else if (document.documentElement && document.documentElement.clientWidth)
    return document.documentElement.clientWidth;
  else
    return document.body.clientWidth;
}

function recenter() {
  var all = $('all');

  var avail  = windowHeight();
  var need   = all.offsetHeight;
  var margin = 0;

  if (avail - need > 0) {
    margin = (avail - need) / 2;
  }

  all.style.marginTop = margin + 'px';
}

var stars = new Array();
var density = 0.0001;
var starSize = 20;

function respangle() {
  var all = $('all');
  var contentWidth = all.offsetWidth;
  var xAvail = windowWidth() - contentWidth;
  var yAvail = windowHeight();
  var avail = xAvail * yAvail;
  var nstars = Math.floor(avail * density);

  /* Resize the cutout photo. */
  var cutout    = $('cutout');
  var cutoutDim = Math.min(xAvail/2 + 100, 580);
  if (cutoutDim > 100) {
    cutout.style.visibility = 'visible';
    cutout.setAttribute('width', Math.floor(cutoutDim));
    cutout.setAttribute('height', Math.floor(cutoutDim));
  } else {
    cutout.style.visibility = 'hidden';
  }

  function addStar() {
    var newimg = document.createElement('img');
    var top    = Math.floor(Math.random() * (yAvail - starSize));
    var left   = Math.floor(Math.random() * (xAvail - 2 * starSize));
    if (left + starSize > xAvail / 2)
      left += contentWidth + starSize;

    newimg.setAttribute('alt', '*');
    newimg.setAttribute('src', 'images/star.png');
    newimg.setAttribute('class', 'twinkle');
    newimg.style.top    = top + 'px';
    newimg.style.left   = left + 'px';
    newimg.style.zIndex = '-1';

    all.appendChild(newimg);
    return newimg;
  }

  if (stars.length < nstars) {
    stars.push(addStar());
    setTimeout('respangle();', 100);
  } else if (stars.length > nstars) {
    all.removeChild(stars.shift());
    setTimeout('respangle();', 100);
  } else {
    for (var i = 0; i < nstars / 3; ++i) {
      all.removeChild(stars.shift());
      stars.push(addStar());
    }
    setTimeout('respangle();', 500);
  }
}

function resizer() {
  recenter();
}

function splash_setup() {
  resizer();
  if(window.addEventListener)
    window.addEventListener('resize', resizer, false);
  else if (document.addEventListener)
    document.addEventListener('resize', resizer, false);
  else if (window.attachEvent)
    window.attacheEvent('onResize', resizer);
  respangle();
}
