var rows;
var loop;
var chr_width;
var chr_height;
var width;
var height;

function Row() {
	this.pos=0;
	this.speed=0;
}
function textWidth(text) {
	field = document.getElementById("textSize");
	field.innerHTML=text;
	return field.clientWidth+1;
}
function textHeight(text) {
	field = document.getElementById("textSize");
	field.innerHTML=text;
	return field.clientHeight;
}
function random(from,to) {
	return Math.random()*(to-from)+from;
}
function windowWidth() {
	if(window.innerWidth) return window.innerWidth;
	if(document.body.offsetWidth) return document.body.offsetWidth;
	return 640;
}
function windowHeight() {
	if(window.innerWidth) return window.innerHeight;
	if(document.body.offsetHeight) return document.body.offsetHeight;
	return 480;
}

function drawMatrix() {
	chr_width=textWidth("X");
	chr_height=textHeight("X");
	width=Math.ceil(windowWidth()/chr_width);
	height=Math.ceil(windowHeight()/chr_height)*2;
	rows = new Array(width);
	for(w=0; w<width; w++) {
		rows[w] = new Row();
		rows[w].pos = Math.round(random(-height*chr_height+1,height*chr_height-1));
		rows[w].speed=random(50,150);
		document.write("<div id='r"+w+"' style='position:absolute;top:"+rows[w].pos+"px;left:"+(w*chr_width)+"px;'>");
		for(i=1; i<=height; i++) {
			chr=String.fromCharCode(random(33,127));
			document.write("<span style='zoom:1;opacity:"+(i/height)+";filter: alpha(opacity = "+(i/height*100)+");'>"+chr+"</span><br>");
		}
		document.write("</div>");
	}
}
function updateMatrix() {
	for(i=0; i<rows.length; i++) {
		rows[i].pos+=rows[i].speed;
		document.getElementById("r"+i).style.top=rows[i].pos+"px";
		if(rows[i].pos>chr_height*height*2*2) rows[i].pos=-chr_height*height;
	}
	loop=setTimeout("updateMatrix()",1);
}
function runMatrix() {
	drawMatrix();
	clearTimeout(loop);
	loop=setTimeout("updateMatrix()",1);
}

