var c;
var ctx;
var img;
var a = 0;

var timer = null;

var pi = 3.141592653589793;

function update() {
/*	Keep this time based so the flower doesn't jump when the page is reloaded (etc). */
	var d = new Date ();
	a = 0.00007 * pi * (d.getTime ());
	ctx.clearRect (0, 0, 192, 192);
	ctx.save ();
	ctx.translate (96,96);
	ctx.rotate (0.04 * Math.sin (a) * Math.cos (a*1.2));
	ctx.drawImage (img, -96, -96);
	ctx.restore ();
}

function replaceCosmos() {
	c = document.createElement ('canvas');			/*	Create an empty <canvas> element. */
	c.setAttribute ('width', '192');
	c.setAttribute ('height', '192');
	if (c.getContext) ctx = c.getContext ('2d');	/*	If possible, get the canvas context. */
	else {delete c; return;}						/*	Otherwise leave it as it is. */

	document.body.setAttribute ('xmlns', 'http://www.apple.com/2004/xhtml-extended/');
													/*	Change the xmlns of the document to keep it valid. */

	img = document.getElementById('MainCosmos');	/*	The rest of the code just replaces the image with the canvas. */
	img.src = img.src.replace (non_alpha_formats, '.png');
													/*	If the UA can handle <canvas>, surely it can handle alpha?
														Actually, Firefox seems to have problems displaying paletted
														png images (with single colour transparency) on a <canvas>. */


/*	At this point, the browser is loading the alpha-png image. Once loaded, the image is replaced with a <canvas>.
	If the page is reloaded, or another page with the same image is loaded, the Cosmos flower will be loaded from cache.
	This makes the transition very fast, and there will be no perceived flicker. */

	img.onload = function () {
		(this.parentNode).replaceChild(c, this);
		img.id = '';	/*	'img' is no longer part of the document and so, if I understand correctly, it can share an
							id value with the canvas element. However, it is being removed here just to be sure. It's no
							longer needed anyway. */
		c.id = 'MainCosmos';

		if (timer) clearInterval (timer);
		update ();
		timer = setInterval ('update ()', 50);
	}
}

var file_canvas = true;
