/hacks/Munch/Munch.js
/* Copyright 2011 The Dominion of Awesome
 * See COPYING for licensing information */
enyo.kind({
	name: 'Munch',
	kind: 'Hack',
	style: "background-color: black",
	align: "center",
	pack: "center",
	preferences: [
		{name: "phosphorColor", label: "Phosphor Color", kind: "ListSelector", items: [
			{caption: "green", value: '#00FF00'},
			{caption: "blue", value: '#3030FF'},
			{caption: "red", value: '#FF2020'},
			{caption: "magenta", value: '#FF20FF'},
			{caption: "cyan", value: '#00FFFF'},
			{caption: "yellow", value: '#FFFF00'},
			{caption: "amber", value: '#9F9F00'}
		]},
		{name: "displayStyle", label: "Style", kind: "ListSelector", items: [
			{caption: "tiled", value: 0},
			{caption: "centered", value: 1}
		]}
	],
	phosphorColor: '#00FF00',
	displayStyle: 0,

	components: [
		{name: "display", nodeTag: "canvas"}
	],

	t: 0,
	timer: null,

	rendered: function() {
		this.display = this.$.display.hasNode();
		this.ctx = this.display.getContext('2d');

		this.intermediate = document.createElement('canvas');
		this.intermediate.width = 512;
		this.intermediate.height = 512;
		this.ictx = this.intermediate.getContext('2d');
		this.ictx.fillStyle = 'black';
		this.ictx.fillRect(0, 0, 255, 255);
		this.ictx.fillStyle = 'rgba(0,0,0,0.075)';
		this.ictx.strokeStyle = this.phosphorColor;

		this.resize(window.innerWidth, window.innerHeight);
		this.draw();
	},

	resize: function(w, h) {
		if (this.displayStyle == 0) {
			this.display.width = this.w = w;
			this.display.height = this.h = h;
		} else {
			this.display.width = 512;
			this.display.height = 512;
		}
	},

	preferencesChanged: function() {
		this.ictx.strokeStyle = this.phosphorColor;
		if (this.displayStyle == 0) {
			this.display.width = this.w;
			this.display.height = this.h;
		} else {
			this.display.width = 512;
			this.display.height = 512;
		}
	},

	draw: function() {
		this.ictx.fillRect(0, 0, 512, 512);
		this.ictx.beginPath();
		for (var x = 0; x < 512; x++) {
			var y = x ^ this.t;
			this.ictx.moveTo(x, y);
			this.ictx.lineTo(x+1, y+1);
		}
		this.ictx.stroke();
		this.t = (this.t + 1) % 512;

		if (this.displayStyle == 0) {
			for (var x = 0; x < this.w; x += 512) {
				for (var y = 0; y < this.h; y += 512) {
					this.ctx.drawImage(this.intermediate, 0, 0, 512, 512, x, y, 512, 512);
				}
			}
		} else {
			this.ctx.drawImage(this.intermediate, 0, 0);
		}
	},

	start: function() {
		if (this.timer) return;
		this.timer = setInterval(this.draw.bind(this), 20);
	},

	stop: function() {
		clearInterval(this.timer);
		this.timer = null;
	}
});