if (typeof susan == 'undefined') susan = {};

susan.clearCanvas = function(canvasId, strokesId) {
	var strokesField = $(strokesId);
	if (strokesField.value != '' && !window.confirm('Are you sure to clear the canvas?')) {
		return;
	}
	strokesField.value = '';
	// TODO should be given as arguments?
	$('parent-key').value = '';
	$('parent-strokes').value = '';
	var ctx = document.getElementById(canvasId).getContext('2d');
	ctx.clearRect(0, 0, 200, 200);
}
susan.initializeCanvas = function(eid, points) {
	var ctx = document.getElementById(eid).getContext('2d');
	ctx.clearRect(0, 0, 200, 200);
	susan.drawCanvas(eid, points);
}
susan.drawCanvas = function(eid, points) {
	//var ctx = susan.getAssuredElementById(eid).getContext('2d');
	var ctx = document.getElementById(eid).getContext('2d');
	var strokes = points.split('|');
	for (var i = 0; i < strokes.length; i++) {
		if (strokes[i] == '') continue;

		var strokeStyle;
		var lineWidth = 2;
		var ps;
		if (strokes[i].match(/^\[(color:)?([^,]+)(,width:(.*))?\]/)) {
			strokeStyle = RegExp.$2;
			if (RegExp.$4 != '') lineWidth = RegExp.$4;
			ps = strokes[i].replace(/^\[(.*)\]/, '').split(',');
		}
		else {
			strokeStyle = '#000000';
			ps = strokes[i].split(',');
		}

		if (1 < ps.length) {
			var p = ps[0].split(':');
			var x = parseInt(p[0]);
			var y = parseInt(p[1]);
			ctx.strokeStyle = strokeStyle;
			ctx.lineWidth = lineWidth;
			ctx.beginPath();
			ctx.moveTo(x, y);
			for (var j = 1; j < ps.length; j++) {
				if (ps[j] == '') continue;

				p = ps[j].split(':');
				x = parseInt(p[0]);
				y = parseInt(p[1]);
				ctx.lineTo(x, y);
			}
			ctx.stroke();
		}
	}
}
/*
susan.getAssuredElementById = function(eid) {
	var elm = document.getElementById(eid);
	if (elm) {
		return elm;
	}
	else {
		return setTimeout(function() {return susan.getAssuredElementById(eid)}, 100);
	}
}
*/
