
var boxwidth=670;
var boxheight=350;
var topmargin=-19;
var leftmargin=0;
var pixsize=10;

var n, i, tmax, t;
var branches, aType, test, turnplusminus;
var nmax; //how many graphs to be shown
var lastX;
var lastY;
var direction;
var p_turn;
var p_bran;

function init() {
	n = 1;
	i = 1;
	branches = 0;
	aType = 1;
	test = 0;
	turnplusminus = 0;
	nmax = 1
	lastX = new Array();
	lastY = new Array();
	lastX[0] = (boxwidth-pixsize)/2;
	lastY[0] = (boxheight-pixsize)/2;
	direction = new Array();
	
	//if (Math.random() < 0.2) {
	//	p_turn = 0.99; 
	//} else { 
	//	p_turn = 0.5;
	//}
	p_turn = 0.1;
	p_bran = 0.8;
}

function displayImage() {
	var tm = 100;
	//if (n > nmax) n = 1;



	if (Math.random() > p_turn) {
		aType = !aType;
	}

	//make new branch//
	if (Math.random() > p_bran) {
		branches = branches + 1;
		if (aType == 1) {
			lastX[branches] = lastX[branches-1]+5*pixsize;// - Math.random()*10*10;
			lastY[branches] = lastY[branches-1];
		} else {
			lastX[branches] = lastX[branches-1];
			lastY[branches] = lastY[branches-1]+7*pixsize;// + Math.random()*10*10;
		}
	}

	//add to current branches//
    for (var i = 0; i <= branches; i++) {
		var el = document.createElement('img');
		el.setAttribute("src", "images/1.png");
		el.id = 'divImageBox' + (nmax + 1);
		nmax = nmax + 1;
		el.style.position = "absolute";

		//which way to turn
		test=Math.random();
		if (test > 0.5) {turnplusminus=1;}
		else {turnplusminus=-1;}


		if (aType == 1) {
			lastX[i] = lastX[i];
			lastY[i] = lastY[i] + pixsize*turnplusminus;
		} else {
			lastX[i] = lastX[i] + pixsize*turnplusminus;
			lastY[i] = lastY[i];
		}

		if (lastX[i] < 0) {
			lastX[i] = lastX[i]+boxwidth;
			}
		if (lastX[i] > (boxwidth-pixsize)) {
			lastX[i] = lastX[i]-boxwidth;
			}
		if (lastY[i] < 0) {
			lastY[i] = lastY[i]+boxheight;
			}
		if (lastY[i] > (boxheight-pixsize)) {
			lastY[i] = lastY[i]-boxheight;
			}

		el.style.top = lastY[i]+topmargin + "px";
		el.style.left = lastX[i]+leftmargin + "px";
		el.style.zIndex = 2;

		document.getElementById("divImageBox").appendChild(el);
	}

	if (n < tmax) {
	   t = setTimeout("displayImage()", tm); //change every tm milliseconds
       n++;
    } else {
    	stopImage();
    }

}
function stopImage() {
	clearTimeout(t)
	n=1;
}

function startImages(maxT) {
	stopImage(); 
	resetdisplayImage(); 
	init();
	tmax = maxT;
	displayImage()
}

function resetdisplayImage() {
	var cell=document.getElementById("divImageBox");
	if ( cell.hasChildNodes() )
	{
	    while ( cell.childNodes.length >= 1 )
	    {
		cell.removeChild( cell.firstChild );       
	    } 
	}
}
