var body = document.getElementsByTagName("body")[0],
    canvas = document.createElement("canvas");

body.appendChild(canvas);

Element.prototype.getElementWidth = function() {
   if (typeof this.clip !== "undefined") {
      return this.clip.width;
   } else {
      if (this.style.pixelWidth) {
         return this.style.pixelWidth;
      } else {
         return this.offsetWidth;
      }
   }
};

var links = document.getElementsByTagName("nav")[0].children;
for(var i=0;i<links.length;i++) {
	var link = links[i];
	var href = link.href;
	href = href.replace("http://","").replace("/","");
	link.innerHTML += '<span class="href">'+href+'</span>';
	link.innerHTML += '<span class="glow"></span>';
	
	link.addEventListener("mouseover",function(e) {
		to_color_stop_static = 0.5;
	});
	link.addEventListener("mouseout",function(e) {
		to_color_stop_static = -1;
	});
}

var michaelvillar_link = document.getElementsByTagName("h1")[0].children[0];
michaelvillar_link.addEventListener("mouseover",function(e) {
	to_color_stop_static = 0.7;
});
michaelvillar_link.addEventListener("mouseout",function(e) {
	to_color_stop_static = -1;
});

var overlay_alpha = 0.8;
var current_x = -1,
	current_y = -1,
	to_x = -1,
	to_y = -1,
	color_stop = 0,
	to_color_stop = -1,
	to_color_stop_static = -1,
	breath_count = 0,
	breath_state = 1,
	breath_delta = 0,
	to_breath_delta = 0;
var speed = 0;
var particles = [];
var global_particles = [];
var overlay = document.getElementsByTagName("canvas")[0];

function loop() {
	speed = -5 + (Math.sqrt(Math.abs(to_x - current_x) * Math.abs(current_x - to_x) + Math.abs(current_y - to_y) * Math.abs(current_y - to_y)));
	speed = speed + (Math.random() * 10);
	if(speed < 0)
		speed = 0;
		
	var treshold = 100;
	if(to_color_stop_static == -1) {
		var t = 0.2;
		var s = speed;
		t = t - (0.10 * Math.abs((treshold - (s > treshold ? treshold : s)) / treshold));
		to_color_stop = t;
	}
	else
	  to_color_stop = to_color_stop_static;
	
	breath_count++;
	if(breath_count > 50) {
  	breath_state = (breath_state == -1) ? 1 : -1;
  	breath_count = 0;
	}
	  
	color_stop = color_stop + (to_color_stop - color_stop) * 0.21;
	to_breath_delta = breath_state * (color_stop / 10);
	breath_delta = breath_delta + (to_breath_delta - breath_delta) * 0.01;
	color_stop = color_stop + breath_delta;
	if(color_stop < 0.1)
	  color_stop = 0.1;
  else if(color_stop > 0.9)
	  color_stop = 0.9;

	if((to_x != -1 && to_y != -1) && (to_x != current_x && to_y != current_y)) {
		if(current_x == -1 || current_y == -1) {
			current_x = to_x;
			current_y = to_y;
		}
		else {
			current_x = current_x + (to_x - current_x) * 0.21;
			current_y = current_y + (to_y - current_y) * 0.21;
		}
	}
	
	var new_particles = [];
	for (var i=0; i < particles.length; i++) {
		var particle = particles[i];
		particle["alpha"] = particle["alpha"] + (0 - particle["alpha"]) * particle["speed"];
		particle["radius"] = particle["radius"] + (1 - particle["radius"]) * particle["speed"];
		particle["current"][0] = particle["current"][0] + (particle["to"][0] - particle["current"][0]) * particle["speed"];
		particle["current"][1] = particle["current"][1] + (particle["to"][1] - particle["current"][1]) * particle["speed"];
		
		if(particle["alpha"] > 0.01)
			new_particles.push(particle);
	}
	particles = new_particles;
	
	new_particles = [];
	for (var i=0; i < global_particles.length; i++) {
		var particle = global_particles[i];
		particle["alpha"] = particle["alpha"] + (particle["to_alpha"] - particle["alpha"]) * particle["speed"] * 2;
		particle["radius"] = particle["radius"] + (1 - particle["radius"]) * particle["speed"];
		particle["current"][0] = particle["current"][0] + (particle["to"][0] - particle["current"][0]) * particle["speed"];
		particle["current"][1] = particle["current"][1] + (particle["to"][1] - particle["current"][1]) * particle["speed"];
		
		if(particle["alpha"] > 0.01 || particle["to_alpha"] > 0)
			new_particles.push(particle);
		if(particle["alpha"] > particle["to_alpha"] - 0.01)
		  particle["to_alpha"] = 0;
	}
	global_particles = new_particles;
	
	var particles_count = Math.round((speed > 100 ? 100 : speed) / 10) - 1;
	for(var i=0;i<particles_count;i++) {
		generate_particle();
	}
	
	if((Math.round((Math.random() * 20)) % 20) == 1)
	  generate_global_particle();
	
	draw();
	
	setTimeout(function() {
		loop();
	},1000 / 50);
}
function continuous_particle_generation() {
	generate_particle();
	setTimeout(function() {
		continuous_particle_generation();
	},250);
}
function move_overlay(x, y) {
	to_x = x;
	to_y = y;
}
function draw() {
	var x = Math.round(current_x),
		y = Math.round(current_y),
		w = overlay.width,
		h = overlay.height;
	var context = overlay.getContext("2d");
	context.clearRect(0, 0, w, h);
	
	// light
	var x0 = x,
		y0 = y,
		r0 = 10,
		x1 = x0,
		y1 = y0,
		r1 = 250;
	var gradient = context.createRadialGradient(x0, y0, r0, x1, y1, r1);
	var max_alpha = 0.3;
	var treshold = 100;
	var s = speed;
	var alpha = (max_alpha * ((treshold - (s > treshold ? treshold : s)) / treshold));
	if(alpha > max_alpha)
		alpha = max_alpha;
	gradient.addColorStop(0, 'rgba(0,0,0,'+0+')');
	gradient.addColorStop(color_stop, 'rgba(0,0,0,'+(alpha + (overlay_alpha - alpha) * 0.8)+')');
	gradient.addColorStop(1, 'rgba(0,0,0,'+overlay_alpha+')');
	context.fillStyle = gradient;
	context.fillRect(x0 - r1, y0 - r1, r1 * 2, r1 * 2);			

	context.fillStyle = 'rgba(0,0,0,'+overlay_alpha+')';
	context.fillRect(0, 0, w, y0 - r1);
	context.fillRect(0, y0 + r1, w, h - (y0 + r1));
	context.fillRect(0, y0 - r1, x0 - r1, 2 * r1);
	context.fillRect(x0 + r1, y0 - r1, w - (x0 + r1), 2 * r1);
	
	// halos
	var halos = [
		{ 'pos' : 0.6, 'size' : 0.08, 'alpha' : 0.02 },
		{ 'pos' : 0.9, 'size' : 0.02, 'alpha' : 0.05 },
		{ 'pos' : 1.1, 'size' : 0.05, 'alpha' : 0.02 },
		{ 'pos' : 1.5, 'size' : 0.2, 'alpha' : 0.01 },
		{ 'pos' : 1.7, 'size' : 0.5, 'alpha' : 0.004 },
		{ 'pos' : 2.5, 'size' : 0.9, 'alpha' : 0.004 }
	];
	var cx = overlay.width / 2;
	var pente = (x0 - cx) / (y0);
	for (var i=0; i < halos.length; i++) {
		var halo = halos[i];
		var hy = y0 * halo['pos'];
		var	hx = cx + hy * pente;
		var size = halo['size'];
		context.beginPath();
		context.arc(hx, hy, r1 * size, 0, Math.PI * 2, false);
		context.closePath();
		context.fillStyle = 'rgba(255,255,255,'+halo['alpha']+')';
		context.fill();
	}
	
	// particles
	for (var i=0; i < particles.length; i++) {
		draw_particle(context, particles[i]);
	};
	for (var i=0; i < global_particles.length; i++) {
		draw_particle(context, global_particles[i]);
	};
}

function draw_particle(context, particle) {
	if(particle['alpha'] > 0.01) {
		context.beginPath();
		context.arc(particle['current'][0], particle['current'][1], particle['radius'], 0, Math.PI * 2, false);
		context.closePath();
		context.fillStyle = 'rgba(255,255,255,'+particle['alpha']+')';
		context.fill();
	}
}

function generate_particle() {
	var particle_speed = (0.02 + Math.random() * 0.1) * 1.4;
	create_particle(current_x + Math.random() * 20 - 10, 
					current_y + Math.random() * 20 - 10, 
					current_x + Math.random() * 200 - 100, 
					current_y + Math.random() * 200 - 100, 
					Math.random() * 3 + 1,
					Math.random(),
					particle_speed);
}
function generate_global_particle() {
	var x = Math.random() * overlay.width,
	    y = Math.random() * overlay.height;
  global_particles.push({
		'from' : [x, y],
		'to' : [x + Math.random() * 400 - 200, y + Math.random() * 400 - 200],
		'current': [x, y],
		'radius': Math.random() * 1 + 0.4,
		'alpha': 0,
		'to_alpha': 0.2 + Math.random() * 0.2,
		'speed': 0.01
	});
}
function create_particle(x1, y1, x2, y2, radius, alpha, speed) {
	particles.push({
		'from' : [x1, y1],
		'to' : [x2, y2],
		'current': [x1, y1],
		'radius': radius,
		'alpha': alpha,
		'speed': speed
	});
}

function update_overlay_size() {
	overlay.width  = window.innerWidth;
	overlay.height = window.innerHeight;
}

body.addEventListener("mousemove",function(e) {
	move_overlay(e.clientX, e.clientY);
});
function touchhandler(e) {
  move_overlay(e.targetTouches[0].pageX, e.targetTouches[0].pageY);
}
body.addEventListener("touchmove",touchhandler);
body.addEventListener("touchstart",touchhandler);
document.addEventListener('touchstart', function(e){ e.preventDefault(); });

window.addEventListener("resize",function(e) {
	update_overlay_size();
});

continuous_particle_generation();
loop();
update_overlay_size();

var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-1526344-8']);
_gaq.push(['_trackPageview']);
(function() {
  var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
  ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
