
var cx = 0; 	// столбец текущей ячейки
var cy = 0; 	// строка текущей ячейки
var cwx1 = 0; // стобец первой ячейки текущего слова
var cwy1 = 0; // строка первой ячейки текущего слова
var cwx2 = 0; // стобец последней ячейки текущего слова
var cwy2 = 0; // строка последней ячейки текущего слова
var cnum = 0; // номер слова текущей ячейки
var cdt = "h"; // "h" | "v"

var isModified = new Boolean(false);
var cells;
var defs;
var net;
var form1;

function storeCookie(cid) {
    var cur = -1;
    var len = 0;
    var type = 0;
    cookie = "";
    for (j = 0; j < net.rows.length; j++)
        for (i = 0; i < net.rows[j].cells.length; i++)
        if (net.rows[j].cells[i].className == "cell")
        if (net.rows[j].cells[i].children[0].value == "")
        cookie = cookie + "_";
    else
        cookie = cookie + net.rows[j].cells[i].children[0].value;

    setCookie(cid, cookie);
    isModified = false;
}

// Заполняет сетку кроссворда из cookie
function restoreCookie(cid) {
    var cookie = getCookie(cid);
    var cur = 0;

    // Загружаю сетку кроссворда
    for (j = 0; j < cells.length; j++) {
        for (i = 0; i < cells[j].length; i++) {
            if (cells[j][i] != null) {
                if (cookie.length > 0 && cur >= 0 && cookie.charAt(cur) != '_') {
                    value = cookie.substr(cur, 1);
                    cells[j][i].value = value;
                }
                cur++;
            }
        }
    }

    // Загружаю разгаданные слова
    var ds = "";
    var i = cookie.indexOf("|");
    if (i >= 0) {
        ds = cookie.substr(i);
        for (j = 0; j < defs.length; j++)
            for (i = 0; i < defs[j].length; i++)
            if (defs[j][i] != null && ds.indexOf(defs[j][i].id) > 0)
            defs[j][i].className = "worddef2";
    }
}

function clearNet() {
    for (var j = 0; j < cells.length; j++)
        for (var i = 0; i < cells[j].length; i++)
        if (cells[j][i] != null) cells[j][i].value = "";
    isModified = true;
}

function toggleDef(event) {
    var def = getTarget(event);
    if (def.className == "worddef")
        def.className = "worddef2";
    else if (def.className == "worddef2")
        def.className = "worddef";
    isModified = true;

    cancelBubble(event);
}

function selectCell(event, cell) {
    cell.focus();
    cancelBubble(event);
}

function focusCell(event) {
    var cell = getTarget(event);
    var xy = cell.id.substr(1, 10).split("_");
    x = xy[0] * 1;
    y = xy[1] * 1;

    cell.select();
    cx = x;
    cy = y;
    if (cells[cwy1][cwx1] != null) cnum = cells[cwy1][cwx1].name.substr(1, 10);
    // расчитываю текущее слово
    if (cwx1 <= cx && cx <= cwx2 && cwy1 <= cy && cy <= cwy2) return;
    setCWClass("i1", "nocell_def");
    cwx1 = cx;
    cwx2 = cx;
    if (cdt == "h") {
        while (cells[cy][cwx1 - 1] != null) cwx1--;
        while (cells[cy][cwx2 + 1] != null) cwx2++;
    }
    cwy1 = cy;
    cwy2 = cy;
    if (cwx1 == cwx2) // проверяем чтобы исключить вариант расчета иксов и игреков из клетки пересечения
    {
        while (cells[cwy1 - 1][cx] != null) cwy1--;
        while (cells[cwy2 + 1][cx] != null) cwy2++;
    }
    cnum = cells[cwy1][cwx1].name.substr(1, 10);
    setCWClass("i1 selected", "nocell_def2");
    cdt = "h";
}

function setCWClass(cl, cl2) {
	if (cl.indexOf("selected")>=0)
		selectCells();
	else
		unselectCells();

    if (cnum > 0) {
        var d;
        if (cwy1 == cwy2) d = 0; else d = 1;
        defcell = defs[d][cnum];
        if (defcell != null) {
            defcell.className = cl2;
            if (defcell.parentNode.parentNode.parentNode.className == "deftable")
                defcell.className = cl2 + "_2";
        }
    }
}

function selectCells()
{
	for (var i = cwx1; i <= cwx2; i++)
		for (var j = cwy1; j <= cwy2; j++)
			if (cells[j][i] != null) cells[j][i].className += " selected";
}

function unselectCells()
{
	for (var i = cwx1; i <= cwx2; i++)
		for (var j = cwy1; j <= cwy2; j++)
			if (cells[j][i] != null) cells[j][i].className = cells[j][i].className.replace(" selected", "");
}

function changeDirection() {
    //	alert(cx+","+cy+"\n"+cwx1+","+cwy1+","+cwx2+","+cwy2);
    // смена горизонтали на вертикаль
    if (cwx2 > cwx1 && (cells[cy - 1][cx] != null || cells[cy + 1][cx] != null)) {
        setCWClass("i1", "nocell_def");
        cwx1 = cx; cwy1 = cy;
        cwx2 = cx; cwy2 = cy;
        while (cells[cwy1 - 1][cx] != null) cwy1--;
        while (cells[cwy2 + 1][cx] != null) cwy2++;
        cnum = cells[cwy1][cwx1].name.substr(1, 10);
        setCWClass("i1 selected", "nocell_def2");
        return;
    }
    // смена вертикали на горизонталь
    if (cwy2 > cwy1 && (cells[cy][cx - 1] != null || cells[cy][cx + 1] != null)) {
        setCWClass("i1", "nocell_def");
        cwx1 = cx; cwy1 = cy;
        cwx2 = cx; cwy2 = cy;
        while (cells[cy][cwx1 - 1] != null) cwx1--;
        while (cells[cy][cwx2 + 1] != null) cwx2++;
        cnum = cells[cwy1][cwx1].name.substr(1, 10);
        setCWClass("i1 selected", "nocell_def2");
    }
}

function keydownCell(event) {
    var cell = getTarget(event);
    var code = getKeyCode(event);
    switch (code) {
        case 32: // Spacebar
            {
                changeDirection();
                cancelBubble(event);
                break;
            }
        case 9:
            {
                cancelBubble(event);
                break;
            }
        case 8:
            {
                if (cells[cy][cx].value != "") {
                    isModified = true;
                    cells[cy][cx].value = "";
                }
                if (cwy1 == cwy2 && cells[cy][cx - 1] != null) cells[cy][cx - 1].focus();
                if (cwx1 == cwx2 && cells[cy - 1][cx] != null) cells[cy - 1][cx].focus();
            }
    }
}

function keyupCell(event) {
    var cell = getTarget(event);
    if (cells[cy][cx] != cell) return;
    var code = getKeyCode(event);
    switch (code) {
        case 35: // End
            cells[cwy2][cwx2].focus();
            break;
        case 36: // Home
            cells[cwy1][cwx1].focus();
            break;
        case 37: // Left
            if (cells[cy][cx - 1] != null) cells[cy][cx - 1].focus();
            else cells[cy][cx].select();
            break;
        case 38: // Up
            if (cells[cy - 1][cx] != null) cells[cy - 1][cx].focus();
            else cells[cy][cx].select();
            break;
        case 39: // Right
            if (cells[cy][cx + 1] != null) cells[cy][cx + 1].focus();
            else cells[cy][cx].select();
            break;
        case 40: // Down
            if (cells[cy + 1][cx] != null) cells[cy + 1][cx].focus();
            else cells[cy][cx].select();
            break;
        case 186: // Ж
        case 59: // Ж
        case 188: // Б
        case 190: // Ю
        case 191: // Ё
        case 192: // Ё
        case 219: // Х
        case 221: // Ъ
        case 222: // Э
        case 46: // Del
            if (cwx1 == cwx2)
                if (cells[cy + 1][cx] != null) cells[cy + 1][cx].focus();
            else cells[cy][cx].select();
            if (cwy1 == cwy2)
                if (cells[cy][cx + 1] != null) cells[cy][cx + 1].focus();
            else cells[cy][cx].select();
            isModified = true;
            break;
    }
    if (code >= 65 && code <= 90) // A..Z
    {
        if (cwx1 == cwx2)
            if (cells[cy + 1][cx] != null) cells[cy + 1][cx].focus();
        else cells[cy][cx].select();
        if (cwy1 == cwy2)
            if (cells[cy][cx + 1] != null) cells[cy][cx + 1].focus();
        else cells[cy][cx].select();
        isModified = true;
    }
}

//	w - ширина
//  h - высота
//  wc - количество слов
function initNet2(w, h, wc) {
		net = document.getElementById("net");
		form1 = document.getElementById("form1");

    cells = new Array(h + 2);
    cells[0] = new Array();
    for (var j = 1; j <= h; j++) {
        cells[j] = new Array(w + 2);
        for (var i = 1; i <= w; i++) {
            var cell = document.getElementById("i" + i + "_" + j);
            if (cell != null)
                cells[j][i] = cell;
        }
    }
    cells[h + 1] = new Array();

    defs = new Array(2);
    defs[0] = new Array();
    defs[1] = new Array();
    for (var k = 1; k <= wc; k++) {
        var obj;
        obj = document.getElementById("h" + k);
        if (obj != null)
            defs[0][k] = obj;
        obj = document.getElementById("v" + k);
        if (obj != null)
            defs[1][k] = obj;
    }

    initNet();
}

function initNet() {
    // Сетка кроссворда
    for (var j = 0; j < cells.length; j++)
        for (var i = 0; i < cells[j].length; i++)
        if (cells[j][i] != null) {
        cells[j][i].ondblclick = changeDirection;
        cells[j][i].onkeydown = keydownCell;
        cells[j][i].onkeyup = keyupCell;
        cells[j][i].onfocus = focusCell;
        //cells[j][i].maxLength = 1;
        cells[j][i].className += " i1";
        cells[j][i].autocomplete = "off";
    }

    var dir = new Array("h", "v");
    for (var j = 0; j <= 1; j++)
        for (var i = 0; i < defs[j].length; i++)
        if (defs[j][i] != null) {
        var obj = document.getElementById(dir[j] + i);
        obj.onclick = selectCellDef;
        if (obj.childNodes.length == 0 || obj.childNodes[0].tagName != "IMG")
	        obj.title = obj.innerHTML.split("<br>").join("").split("<BR>").join("");
        obj.className = "nocell_def";
        if (obj.parentNode.parentNode.parentNode.className == "deftable")
            obj.className = "nocell_def_2";
    }
}

// устанавливает клетку с определением для текущего слова
function selectCellDef(event) {
    var obj = getTarget(event);
    if (obj.tagName != "TD")
    	obj = obj.parentNode;
    var d = obj.id.substr(0, 1);
    var num = obj.id.substr(1, 10);
    var cells = document.getElementsByName("n" + num);
    if (cells.length > 0)
        var cell = cells[0];

    cdt = d;
    setCWClass("i1", "nocell_def");
    cwx1 = 0; cwx2 = 0; cwy1 = 0; cwy2 = 0;
    cell.focus();
}

// включает/выключает раздел div
function ToggleDiv(event, div) {
    if (div.style.display == "none")
        div.style.display = "block";
    else
        div.style.display = "none";
    cancelBubble(event);
}
