document.observe('dom:loaded', function() {
	canvas.initialize();
});

var canvas = {
	initialize: function() {
		var element = $('moire');
		var context = element.getContext('2d');
		
		var dimensions = document.viewport.getDimensions();
		dimensions.height -= 32;
		['width', 'height'].each(function(i) {
			element.setAttribute(i, dimensions[i]);
		});
		
		this.canvas = element;
		this.context = context;
		this.angle_top = -45;
		this.angle_bottom = -45;
		this.lines = true;
		this.step = this.lines ? 3 : 12;
		
		this.controller_top = new Controller('top', function(v) {
			canvas.step = v;
			canvas.changed = true;
		}, 3, 12);
		
		this.controller_bottom = new Controller('bottom', function(v) {
			canvas.angle_bottom = v;
			canvas.changed = true;
		}, -45, -35);
		
		setInterval(function() {
			if (canvas.changed) {
				canvas.changed = false;
				canvas.rotate();
			}
		}, 300);
		
		this.redraw(this.angle_top, this.angle_bottom);
	},
	toggle: function() {
		this.lines = this.lines ? false : true;
		this.step = this.lines ? 7 : 12;
		this.redraw(this.angle_top, this.angle_bottom);
	},
	redraw: function(top, bottom) {
		this.context.save();
		this.clear_all();
		
		this.draw(top);
		this.draw(bottom);
		
		if (this.lines) {
			this.context.stroke();
		}
		this.context.restore();
	},
	draw: function(angle, color) {
		for (var i=-this.canvas.width*1.5, len=this.canvas.width*1.5; i<len; i+=this.step) {
			this.context.save();
			this.context.translate(this.canvas.width/2, this.canvas.height/2);
			this.context.rotate(this.to_r(angle));
			if (this.lines) {
				this.context.moveTo(i-this.canvas.width/2, 0-this.canvas.height*2);
				this.context.lineTo(i-this.canvas.width/2, this.canvas.height * 2);
			} else {
				this.context.fillStyle = 'black';
				for (var y=-this.canvas.height*1.5; y<this.canvas.height*1.5; y+=this.step) {
					this.context.beginPath();
		    		this.context.arc(i-this.canvas.width/2, y-this.canvas.height/2, 1, 0, Math.PI*2, true);
					this.context.fill();
				}
			}
			this.context.restore();
		}
	},
	rotate: function() {
		this.redraw(this.angle_top, this.angle_bottom);
	},
	clear_all: function() {
		this.context.fillStyle = 'white';
		this.context.beginPath();
		this.context.rect(0, 0, this.canvas.width, this.canvas.height);
		this.context.fill();
	},
	to_r: function(angle) {
		return angle * Math.PI / 180;
	}
}

var Controller = Class.create({
	initialize: function(element, onchange, min, max, floor) {
		this.value = 0;
		var element = $(element), map = this.map, value = this.value;
		element.observe('scroll', function() {
			value = map(element.scrollLeft, 0, element.scrollWidth, min, max);
			if (floor) {
				value = Math.floor(value);
			}
			onchange(value);
		});
	},
	map: function(value, istart, istop, ostart, ostop) {
		return ostart + (ostop - ostart) * ((value - istart) / (istop - istart));
	}
});