var max_particles = 600;
var num_particles = 50;
var fps = 20;
var w = 780;
var h = 80;

var x = [];
var y = [];
var sfs = [];
var fall = [];
var step = [];
var currStep = [];
var theFlakes = [];

var idx = document.getElementsByTagName('div').length;
var offsx;

var adjust_interval;
var adjust_particles = num_particles;
var actual_fps = fps;

for (i = 0; i < max_particles; i++)
{
	initFlake( i );
	document.write( '<div id="flake'+(idx+i)+'" style="position:absolute;top:-2px;left:0px;width:'+sfs[i]+'px;height:'+sfs[i]+'px;z-index:'+sfs[i]+';background-color:#ffffff;font-size:'+sfs[i]+'px"><\/div>' );
}

if( window.addEventListener )
{
 	window.addEventListener( "resize", getOffset, false );
	window.addEventListener( "load", init, false);
} else if (window.attachEvent)
{
	window.attachEvent( "onresize", getOffset );
	window.attachEvent( "onload", init );
} 

function init()
{
	getOffset();

	for (i = 0; i < max_particles; i++)
	{
		theFlakes[i] = document.getElementById( "flake" + (idx + i) ).style;
		if (i < num_particles)
			y[i] = Math.round( Math.random() * h );
	}

	window.setInterval( "animateFlakes()", 1000 / fps );
	adjust_interval = window.setInterval( "adjustFlakes()", 1000 );
}

function initFlake( n )
{
	x[n] = Math.round( Math.random() * (w-5) );
	y[n] = 0;
	sfs[i] = Math.round( 1 + Math.random() );
	fall[n] = (sfs[n] == 1) ? Math.round( 2 + Math.random() * 2 ): Math.round( 3 + Math.random() * 2 );
	step[n] = (sfs[n] == 1) ? 0.05 + Math.random() * 0.1 : 0.05 + Math.random() * 0.05;
	currStep[n] = Math.random() * 6;
}

function animateFlakes()
{
	for( i = 0; i < num_particles; i++ )
	{
		var tx = (x[i] += fall[i] * Math.cos(currStep[i] += step[i])); 
		var ty = (y[i] += fall[i]);

		if (tx < 3 || tx > w - 5 || ty > h)
			initFlake( i );

		theFlakes[i].left = tx + offsx + "px";
		theFlakes[i].top = ty + "px";
	}

	if( num_particles < adjust_particles )
		num_particles += 2;

	actual_fps++;
}

function adjustFlakes()
{
	if (actual_fps < fps - 1)
	{
		num_particles -= 30;
		adjust_particles = num_particles;
		
		for( i = num_particles; i < num_particles + 30; i++ )
			theFlakes[i].top = "-2px";
		
		window.clearInterval( adjust_interval );
	} else if (num_particles + 25 < max_particles)
		adjust_particles = num_particles + 20;

	actual_fps = 0;
}

function getOffset()
{
	var obj = document.getElementById( "page_header" );

	if (obj.x)
		offsx = obj.x;
	else if (obj.offsetParent)
	{
		offsx = 0;
		while (1) 
		{
			offsx += obj.offsetLeft;
			if (!obj.offsetParent)
				return;
			obj = obj.offsetParent;
		}
	}
}