var cw_canvas;
var cw_context;
var cw_cellSize;

var cw_legendBg = '#D8D8D8';
var cw_legendColor = '#606060';
var cw_defaultBg = 'white';
var cw_resultBg = 'yellow';
var cw_color = 'black';
var cw_legendFont = 'normal 10px courier';
var cw_selectedCell;

var cw_id;

var cw_field;
var cw_legend;

var cw_actualLegend = 0;

function cw_drawGrid() {
	var width = cw_field[0].length;
	var height = cw_field.length;
	cw_canvas = document.getElementById(cw_id);
        cw_context = cw_canvas.getContext('2d');
	cw_setColor();
	cw_setCellSize(width, height);
	for (var r = 0; r < height; r++) {
		for (var c = 0; c < width; c++) {
			cw_drawCell(r, c, cw_field[r][c]);
		}
	}
	cw_context.stroke();
}

function cw_drawCell(y, x, type) {
	switch(type) {
		case '#': cw_context.fillStyle = cw_legendBg; break;
		case '?': cw_context.fillStyle = cw_resultBg; break;
		case '_':
		default : cw_context.fillStyle = cw_defaultBg;
	}
	cw_context.strokeStyle = cw_legendColor;
	cw_context.fillRect(x*cw_cellSize+1, y*cw_cellSize+1, cw_cellSize-1, cw_cellSize-1);
	cw_context.strokeRect(x*cw_cellSize, y*cw_cellSize, cw_cellSize, cw_cellSize);
	if (type == '#') {	
		cw_drawLegend(x, y, cw_legend[cw_actualLegend++]);
	} else {
		cw_drawSolution(x, y);
	}
}

function cw_drawLegend(x, y, text) {
	if (cw_context.fillText) {
		cw_context.fillStyle = cw_color;
		cw_context.font = cw_legendFont;
	        var slash = -1;
	        var charsInLine = 10;
	        if ((slash = text.indexOf('/')) > 0) {
			cw_drawSplitLine(x, y);
	        	var right = text.substring(0, slash);
	                var down = text.substring(slash+1, text.length);
			for (var i = 0; i < 3; i++) {
	                        var towrite = right.substring(Math.min(i*charsInLine, right.length), Math.min(charsInLine*(i+1), right.length));
	                        cw_context.fillText(Strings.trim(towrite), x*cw_cellSize + 2, y*cw_cellSize + 10 + i*11);
	                }
			for (var i = 0; i < 3; i++) {
                	        var towrite = down.substring(Math.min(i*charsInLine, down.length), Math.min(charsInLine*(i+1), down.length));
				cw_context.fillText(Strings.trim(towrite), x*cw_cellSize + 2, y*cw_cellSize + 43 + i*11);
        	        }
		} else {
			for (var i = 0; i < 4; i++) {
	        	        var towrite = text.substring(Math.min(i*charsInLine, text.length), Math.min(charsInLine*(i+1), text.length));
				if (cw_context.fillText)
					cw_context.fillText(Strings.trim(towrite), x*cw_cellSize + 2, y*cw_cellSize + 10 + i*12);
			}
       		}
	}
}

function cw_onClickCrossword(e) {
	var cursor = Events.getCursorPosition(e, cw_canvas);
	var x = Math.floor(cursor.x / cw_cellSize);
	var y = Math.floor(cursor.y / cw_cellSize);
	cw_selectCell(x, y);
}

function cw_selectCell(x, y) {
	if (cw_field[y][x] && cw_field[y][x] != '#') {
		if (cw_selectedCell) {
			clearTimeout(cw_selectedCell.cursorTimer);
			cw_drawSolution(cw_selectedCell.x, cw_selectedCell.y);
		}
		cw_selectedCell = {x : null, y : null, cursorTimer : null };
		cw_drawCursor(x, y, 'black');
	}
}

function cw_drawSolution(x, y) {
	cw_context.fillStyle = cw_defaultBg;
	cw_context.fillRect(x*cw_cellSize + 8, y*cw_cellSize + 8, cw_cellSize-16, cw_cellSize-16);
	if (cw_field[y][x] != '#' && cw_field[y][x] != '?' && cw_field[y][x] != '_') {
		cw_context.fillStyle = cw_color;
        	cw_context.font = 'normal 50px arial';
	        cw_context.fillText(""+cw_field[y][x], cw_selectedCell.x*cw_cellSize + 10, cw_selectedCell.y*cw_cellSize + cw_cellSize - 15);
	}
}


function cw_drawCursor(x, y, col) {
	cw_selectedCell.x = x;
	cw_selectedCell.y = y;
	if (col) {
		cw_context.fillStyle = col;
		cw_context.fillRect(x*cw_cellSize + 10, y*cw_cellSize + 10, 1, cw_cellSize - 20);
		col = '';
	} else {
		cw_drawSolution(x, y);
		col = cw_color;
	}
	cw_selectedCell.cursorTimer = setTimeout("cw_drawCursor(" + x + "," + y + ", '"+col+"')", 500);
}

function cw_drawSplitLine(x, y) {
	cw_context.moveTo(x*cw_cellSize, y*cw_cellSize + cw_cellSize/2);
        cw_context.lineTo(x*cw_cellSize+cw_cellSize, y*cw_cellSize + cw_cellSize/2);
}

function cw_setCellSize(width, height) {
	cw_cellSize = Math.floor(Math.min((cw_canvas.width-2)/width, (cw_canvas.height-2)/height));
}

function cw_setColor() {
	cw_context.strokeStyle = "black";
}

function cw_insertCharEvent(e) {
	var key = Events.getKey(e);
	//characters
	if (cw_selectedCell && (key > 64 && key < 91)) {
		cw_field[cw_selectedCell.y][cw_selectedCell.x] = String.fromCharCode(key);
		cw_drawSolution(cw_selectedCell.x, cw_selectedCell.y);
	//tab
	} else if (key == 9) {
		if (cw_selectedCell) {
			var val = '#';
			var x = cw_selectedCell.x;
			var y = cw_selectedCell.y;
			while (val == '#') {
				if (x > cw_field[0].length-2) {
					x = 1;
					y = y+1;	
				} else {
					x = x+1;
				}
				if (y > cw_field.length-2)
					y = 1;
				val = cw_field[y][x];
			}		
			cw_selectCell(x, y);
		} else {
			cw_selectCell(1, 1);
		}
	//left
	} else if (key == 37) {
		if (cw_selectedCell) {
			var val = '#';
			var x = cw_selectedCell.x;
                	var y = cw_selectedCell.y;
	                while (val == '#') {
        	        	x = (x == 1) ? cw_field[0].length-1 : x-1;
	                        val = cw_field[y][x];
                	}
	                cw_selectCell(x, y);
		} else {
			cw_selectCell(1, 1);
		}
	} else if (key == 38) {
                if (cw_selectedCell) {
                        var val = '#';
                        var x = cw_selectedCell.x;
                        var y = cw_selectedCell.y;
                        while (val == '#') {
                                y = (y == 1) ? cw_field.length-1 : y-1;
                                val = cw_field[y][x];
                        }
                        cw_selectCell(x, y);
                } else {
                        cw_selectCell(1, 1);
                }
	} else if (key == 39) {
                if (cw_selectedCell) {
                        var val = '#';
                        var x = cw_selectedCell.x;
                        var y = cw_selectedCell.y;
                        while (val == '#') {
                                x = (x == cw_field[0].length-1) ? 1 : x+1;                                
                                val = cw_field[y][x];
                        }
                        cw_selectCell(x, y);
                } else {
                        cw_selectCell(1, 1);
                }
	} else if (key == 40) {
                if (cw_selectedCell) {
                        var val = '#';
                        var x = cw_selectedCell.x;
                        var y = cw_selectedCell.y;
                        while (val == '#') {
                                y = (y == cw_field.length-1) ? 1 : y+1;
                                val = cw_field[y][x];
                        }
                        cw_selectCell(x, y);
                } else {
                        cw_selectCell(1, 1);
                }
	//backspace
	} else if (key == 46 || key == 8) {
		if (cw_selectedCell) {
			cw_field[cw_selectedCell.y][cw_selectedCell.x] = "_";
			cw_drawSolution(cw_selectedCell.x, cw_selectedCell.y);
		}
	}
}

function cw_setActions() {
    cw_canvas.setAttribute("onclick", "cw_onClickCrossword()");
    cw_canvas.onclick = cw_onClickCrossword;
    document.onkeydown = cw_insertCharEvent;
}

function cw_setDefinition(field, legend) {
      cw_field = field;
      cw_legend = legend;
}

function cw_setId(id) {
	cw_id = id;
}

function cw_init() {
	cw_drawGrid();
	cw_setActions();
}

window.onload = cw_init;

