
var cx = 0; 	// столбец текущей ячейки
var cy = 0; 	// строка текущей ячейки
var cwx1 = 0; // стобец первой ячейки текущего слова
var cwy1 = 0; // строка первой ячейки текущего слова
var cwx2 = 0; // стобец последней ячейки текущего слова
var cwy2 = 0; // строка последней ячейки текущего слова
var cdt = ""; // текущее напрвление "h"|"v"

var isModified = new Boolean(false);
var cells;
var defs;

function storeCookie(cid) {
    var cur = -1;
    var len = 0;
    var type = 0;
    var cookie = "";
    var net = document.getElementById("net");
    for (var j = 0; j < net.rows.length; j++)
        for (var i = 0; i < net.rows[j].cells.length; i++) {
        if (net.rows[j].cells[i].className == "cell") {
            if (net.rows[j].cells[i].childNodes[0].value == "")
                cookie = cookie + "_";
            else
                cookie = cookie + net.rows[j].cells[i].childNodes[0].value;
        }
    }

    // Перебираем все определения и сохраняем помеченые
    var s = "|";
    var defs = document.getElementById("hdef").getElementsByTagName("A");
    for (i = 0; i < defs.length; i++)
        if (defs[i] != null && defs[i].className == "worddef2")
        s = s + "," + defs[i].id;

    defs = document.getElementById("vdef").getElementsByTagName("A");
    for (i = 0; i < defs.length; i++)
        if (defs[i] != null && defs[i].className == "worddef2")
        s = s + "," + defs[i].id;

    cookie = cookie + s;
    setCookie(cid, cookie);
    isModified = false;
}

// Заполняет сетку кроссворда из cookie
function restoreCookie(cid) {
    var cookie = getCookie(cid);
    var cur = 0;

    // Загружаю сетку кроссворда
    for (var j = 0; j < cells.length; j++) {
        for (var i = 0; i < cells[j].length; i++) {
            if (cells[j][i] != null) {
                var value = "";
                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() {
    var net = document.getElementById("net");
    for (var j = 0; j < net.rows.length; j++)
        for (var i = 0; i < net.rows[j].cells.length; i++) {
        if (net.rows[j].cells[i].className == "cell")
            net.rows[j].cells[i].childNodes[0].value = "";
    }
    for (j = 0; j < defs.length; j++)
        for (i = 0; i < defs[j].length; i++) {
        if (defs[j][i] != null)
            defs[j][i].className = "worddef";
    }
    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(cell, dt) {
    cdt = dt;
    cell.focus();
    cancelBubble(event);
}

function f1(event) {
    cancelBubble(event);
}

function focusCell(event) {
    var cell = getTarget(event);
    var xy = cell.id.substr(1, 10).split("_");
    var x = xy[0] * 1;
    var y = xy[1] * 1;

    cell.select();
    cx = x;
    cy = y;
    // расчитываю текущее слово
    if (cwx1 <= cx && cx <= cwx2 && cwy1 <= cy && cy <= cwy2 && cdt == "") return;
    setCWClass("i1");
    cwx1 = cx;
    cwx2 = cx;
    if (cdt != "v") {
        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++;
    }
    setCWClass("i1 selected");
    cdt = "";
}

function setCWClass(cl) {
	if (cl.indexOf("selected") >= 0)
		selectCells();
	else
		unselectCells();
}

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");
        cwx1 = cx; cwy1 = cy;
        cwx2 = cx; cwy2 = cy;
        while (cells[cwy1 - 1][cx] != null) cwy1--;
        while (cells[cwy2 + 1][cx] != null) cwy2++;
        setCWClass("i1 selected");
        return;
    }
    if (cwy2 > cwy1 && (cells[cy][cx - 1] != null || cells[cy][cx + 1] != null)) {
        setCWClass("i1");
        cwx1 = cx; cwy1 = cy;
        cwx2 = cx; cwy2 = cy;
        while (cells[cy][cwx1 - 1] != null) cwx1--;
        while (cells[cy][cwx2 + 1] != null) cwx2++;
        setCWClass("i1 selected");
    }
}

function keydownCell(event) {
    var cell = getTarget(event);
    switch (getKeyCode(event)) {
        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) {
    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";
        if (cells[j][i].name != null) // клетка с номером
        {
            var title = "";
            var num = cells[j][i].name.substr(1, 10);
            var h = document.getElementById("h" + num);
            if (h != null)
                title = "По горизонтали:\n" + getInnerText(h);
            var v = document.getElementById("v" + num);
            if (v != null) {
                if (h != null) title += "\n";
                title += "По вертикали:\n" + getInnerText(v);
            }
            if (title != "")
                cells[j][i].title = title;
            //					cells[j][i].style.background = "url('/kp/"+num+".png')";
        }
    }

    // определения
    for (var j = 0; j < defs.length; j++)
        for (var i = 0; i < defs[j].length; i++)
        {
            if (defs[j][i] != null) {
                defs[j][i].oncontextmenu = toggleDef;
                defs[j][i].title = "Кликните, чтобы попасть на первую клетку слова";
                defs[j][i].onclick = selectCellDef;
                defs[j][i].className = "worddef";
                defs[j][i].href = "javascript:;";
            }
        }
}

// устанавливает клетку с определением для текущего слова
function selectCellDef(event) {
    cancelBubble(event);

    var obj = getTarget(event);
    if (obj.tagName != "A") obj = obj.parentElement;
    var d = obj.id.substr(0, 1);
    var num = obj.id.substr(1, 10);
    var cells = document.getElementsByName("n" + num);
    if (cells.length > 0) {
        cdt = d;
        cells[0].focus();
    }
}
