function newflake(id, data) {
	n = document.createElement('div');
	n.setAttribute('id',id);
	n.setAttribute('class','flake');
	p = document.createElement('a');
	p.setAttribute('href', data.url);
	p.setAttribute('class','flake_preview');
	img = document.createElement('img');
	img.setAttribute('src','flake.png');
	p.appendChild(img);
	n.appendChild(p);
	namediv = document.createElement('div');
	namediv.appendChild(document.createTextNode(data.name));
	n.appendChild(namediv);
	document.body.appendChild(n);
	return n;
}

var flakes;
var enginetimer = null;

function startengine(data) {
	if (enginetimer)
		clearTimeout(enginetimer);
	flakes = new Array();
	for (key in data) {
		f = new Object();
		f.x = Math.floor(Math.random() * window.innerWidth);
		f.y = -Math.floor(Math.random() * 480);
		f.direction = (Math.random() * 6) - 3;
		f.flake = newflake(key, data[key]);
		flakes.push(f);
	}
	engine();
}

function engine() {
	for (f in flakes) {
		flakes[f].y += 2;
		if (flakes[f].y > window.innerHeight) {
			flakes[f].y = -300;
			flakes[f].x = Math.floor(Math.random() * window.innerWidth);
			flakes[f].direction = (Math.random() * 6) - 3;
		}
		// Simulated brownian motion
		flakes[f].direction += (Math.random() * 4) - 2;
		flakes[f].x += flakes[f].direction * 0.2;
		flakes[f].flake.setAttribute('style','top:' + flakes[f].y + 'px;left:' +
			flakes[f].x + 'px');
	}
	enginetimer = setTimeout('engine()',50);
}

function popout_upload() {
	show('uploader');
	hide('upload_link');
}

function upload_cancel() {
	hide('uploader');
	show('upload_link');
}

function upload_start() {
	hide('uploader');
	show('upload_twirly');
	document.getElementById('uploader').submit();
	upload_twirly();
}

twirly_count = 0;

function upload_twirly() {
	var twirly = document.getElementById('upload_twirly');
	while (twirly.firstChild)
		twirly.removeChild(twirly.firstChild);
	var twirlytext;
	switch (twirly_count++) {
	case 0:
		twirlytext = '/';
		break;
	case 1:
		twirlytext = '-';
		break;
	case 2:
		twirlytext = '\\';
		break;
	case 3:
		twirlytext = '|';
	}
	twirly_count = twirly_count % 4;
	twirly.appendChild(document.createTextNode(twirlytext));
	setTimeout('upload_twirly()',100);
}

function hide(id) {
	document.getElementById(id).setAttribute('style','display: none');
}

function show(id) {
	document.getElementById(id).removeAttribute('style');
}
