var ctx
var coordinates = {top: 0, left: 0}
var mapindex = 0
var width = 5
var color = 0
var mapping = new Array

$(function() {
	var canvas = document.getElementById("canvas")
	if (canvas.getContext) {
		ctx = canvas.getContext("2d")
		saveMapping()
		hilbert(5, 1, 1)
		animate()
	}
})

;window.requestAnimFrame = (function(){
	return	window.requestAnimationFrame       || 
			window.webkitRequestAnimationFrame || 
			window.mozRequestAnimationFrame    || 
			window.oRequestAnimationFrame      || 
			window.msRequestAnimationFrame     || 
			function(callback, element) {
            	window.setTimeout(callback, 1000 / 60)
          }
})()

;function animate() {
	for (var i = 0; i < 1024; i++) {
		var left = mapping[i][0]
		var top = mapping[i][1]
		
		var col = Math.round((360*color/1024)) % 90

		ctx.clearRect(left*width, top*width, width, width)
		ctx.fillStyle = "hsl(" + Math.round((360*color/1024)) % 360 + ", 100%, 50%)"
		ctx.fillRect(left*width, top*width, width, width)

		if (col <= 4 && col > 0) 
			ctx.fillStyle = "hsla(0, 100%, 0%, " + ((col/16)+0.4) + ")"
		else if (col <= 8 && col > 4) 
			ctx.fillStyle = "hsla(0, 100%, 0%, 0.65)"
		else if (col <= 12 && col > 8)
			ctx.fillStyle = "hsla(0, 100%, 0%, " + (0.65 - ((col-8)/16)) + ")"

		ctx.fillRect(left*width, top*width, width, width)
		color = (color + 1) % 1024
	}
	color++
	timeout = window.requestAnimFrame(animate, 0)
}


function left(direction, rotation) {
	return (direction + rotation + 2) % 4
}

function right(direction, rotation) {
	return (direction - rotation + 2) % 4
}

function forward(direction) {
	switch (direction) {
		case 0:
			coordinates.top--
			break
		case 1:
			coordinates.left++
			break
		case 2:
			coordinates.top++
			break
		case 3:
			coordinates.left--
			break
	}
	saveMapping()
}

function saveMapping() {
	mapping[mapindex] = new Array
	mapping[mapindex][0] = coordinates.left
	mapping[mapindex][1] = coordinates.top
	mapindex++
}

function hilbert(level, direction, rotation) {
	if (level == 0)
		return

	direction = right(direction, rotation)

	hilbert(level - 1, direction, -rotation)
	forward(direction)
	

	direction = left(direction, rotation)

	hilbert(level - 1, direction, rotation)
	forward(direction)


	hilbert(level - 1, direction, rotation)

	direction = left(direction, rotation)
	forward(direction)
	hilbert(level - 1, direction, -rotation)
}

var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-28631841-1']);
_gaq.push(['_setDomainName', 'peksa.se']);
_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);
})();

