// canvas@tomtheisen.com
// http://tomtheisen.com/spread/

var startradius = 20;
var width = 1024;
var height = 800;
var frame_time = 60;
var straighten_factor = 0.95;
var curviness = 0.05;
var color_speed = 0.03;
var new_branch_frames = 20;
var branch_shrink = 0.95;
var branch_opacity = 0.4;

var paper;
var branches = [];
var direction_offset = 0;
var frame = 0;
var fadecheck;
var cyclecheck;
var randomizecheck;
var wrapcheck;


function create_tree(x, y) {
	branches.push(new Branch(x, y, 0, startradius));
	branches.push(new Branch(x, y, Math.PI * 2 / 3, startradius));
	branches.push(new Branch(x, y, Math.PI * 4 / 3, startradius));
}

function Branch(x, y, direction, radius) {
	this.x = x;
	this.y = y;
	this.radius = radius;
	this.original_radius = radius;
	this.direction = direction;
}

function clock_tick() {

	if (cyclecheck) {
		r = Math.floor(Math.sin(frame * color_speed) * 128 + 128)
		g = Math.floor(Math.sin(frame * color_speed + Math.PI * 2 / 3) * 128 + 128)
		b = Math.floor(Math.sin(frame * color_speed + Math.PI * 4 / 3) * 128 + 128)
		paper.strokeStyle = "rgba(" + r + "," + g + "," + b + ", " + branch_opacity + ")";
	}

	if(++frame % new_branch_frames == 0) {
		if (randomizecheck) {
			x = (Math.random() + 0.1) * width * 0.8;
			// y = (Math.random() + 0.1) * height * 0.8
			y = height / 2
			create_tree(x, y);
		} else {
			create_tree(width / 2, height / 2);
		}
	}

	direction_offset += Math.random() * curviness - curviness / 2;
	direction_offset *= straighten_factor;

	for (var i = branches.length - 1; i >= 0; i--) {
		var branch = branches[i];

		paper.beginPath();
		paper.lineWidth = branch.radius;
		paper.moveTo(branch.x, branch.y);

		branch.radius *= branch_shrink;
		branch.direction += direction_offset;
		branch.x += Math.cos(branch.direction) * branch.radius;
		branch.y += Math.sin(branch.direction) * branch.radius;

		paper.lineTo(branch.x, branch.y);
		paper.stroke();

		if (wrapcheck) {
			if (branch.x > width) branch.x -= width;
			if (branch.x < 0) branch.x += width;
			if (branch.y > height) branch.y -= height;
			if (branch.y < 0) branch.y += height;
		}

		if (branch.radius < branch.original_radius / 2) {
			branches.splice(i, 1);
			var new_radius = branch.original_radius / 2;
			if (new_radius > 1) {
				branches.push(new Branch(branch.x, branch.y, branch.direction,     new_radius));
				branches.push(new Branch(branch.x, branch.y, branch.direction + 1, new_radius));
			}
		}
	}
}

function startSpread() {
	fadecheck = false; //  Fade
	cyclecheck = true; // Cycle colors
	randomizecheck = true; // Randomize Position
	wrapcheck = false; // Wrap Edges

	paper = document.getElementById("backgroundCanvas").getContext("2d");
	paper.strokeStyle = "rgba(128,128,64," + branch_opacity + ")";


	setInterval(clock_tick, frame_time);
}
