var tileWidth = 33;
var tileHeight = 39;
var tileChars = "1234567890/";

window.requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || function (callback) {
	setTimeout(callback, 16);
}

function createCountdown(containerId, charsImageUrl, timestamp) {
	
	var image = new Image();
	
	image.onload = function () {
		
		var canvas = document.createElement("canvas");
		canvas.width = tileWidth * 15;
		canvas.height = tileHeight;
		
		var ctx = canvas.getContext("2d");
		
		var container = document.getElementById(containerId);
		container.appendChild(canvas);
		
		var updateCountdown = function () {
			
			var now = new Date().getTime();
			var duration = Math.max(0, timestamp - now)
			
			drawDigits(ctx, image, duration);
			
			window.requestAnimationFrame(updateCountdown);
		};
		
		window.requestAnimationFrame(updateCountdown);
	};
	
	image.src = charsImageUrl;
}

var drawnChars = "";

function drawDigits(ctx, digitsImage, milliseconds) {
	
	var days = Math.floor(milliseconds / 1000 / 60 / 60 / 24);
	milliseconds -= days * 24 * 60 * 60 * 1000;
	
	var hours = Math.floor(milliseconds / 1000 / 60 / 60);
	milliseconds -= hours * 60 * 60 * 1000;
	
	var minutes = Math.floor(milliseconds / 1000 / 60);
	milliseconds -= minutes * 60 * 1000;
	
	var seconds = Math.floor(milliseconds / 1000);
	milliseconds -= seconds * 1000;
	
	if (days > 999) {
		days = 999;
		hours = 99;
		minutes = 99;
		seconds = 99;
		milliseconds = 999;
	}
	
	var dd = zeroPad(days, 3);
	var hh = zeroPad(hours, 2);
	var mm = zeroPad(minutes, 2);
	var ss = zeroPad(seconds, 2);
	var ms = zeroPad(milliseconds, 3); // Shows only 2
	
	var str = dd + "/" + hh + "/" + mm + "/" + ss + "/" + ms.charAt(0) + ms.charAt(1);

	var x = 0;
	
	for (var i = 0; i < str.length; i++) {
		
		var chr = str.charAt(i);
		var prevChr = drawnChars.charAt(i);
		
		if (chr != prevChr) {
			
			var sx = tileChars.indexOf(chr) * tileWidth;
			
			if (sx >= 0) {
				ctx.drawImage(digitsImage,
					sx, 0, tileWidth, tileHeight,
					x, 0, tileWidth, tileHeight);
			}
		}
		
		x += tileWidth;
	}
	
	drawnChars = str;
}

function zeroPad(value, size) {
	var str = "" + value;
	while (str.length < size) {
		str = "0" + str;
	}
	return str;
}
