//////////////////////////////////////////////////////////////////
// USER CROSSWORDS
//////////////////////////////////////////////////////////////////
var lastSelectedQuestion = "";
var showQuestionCheck = true;
var rightMenuVisible = "";
var lastTypedBox = '';
var directionWriting = "horizontal";
var alphabeta = new Array("А", "Б", "В", "Г", "Д", "Е", "Ж", "З", "И", "Й",
                          "К", "Л", "М", "Н", "О", "П", "Р", "С", "Т", "У",
                          "Ф", "Х", "Ц", "Ч", "Ш", "Щ", "Ъ", "Ь", "Ю", "Я");

function showQuestions(obj, x, y, crosswordId){
    $('question_shown').innerHTML = "";
    
    hideQuestions();
    
    $("black_box_"+x+"_"+y).className = "question_mark";
    lastSelectedQuestion = "black_box_"+x+"_"+y;
    
    // взима позицията на самия въпрос
    position = findPos($(obj));
    left = position[0];
    top = position[1];
    
    // взима позицията на контеинера на кръстословицата
    theCrosswordPosition = findPos($("the_crossword"));
    theCrosswordLeft = theCrosswordPosition[0];
    theCrosswordTop = theCrosswordPosition[1];
    
    // изчислява се къде да се появят въпросите
    // при положение, че контеинера е с релативна позиция (position: relative;) в css-а
    left = left - theCrosswordLeft;
    top = top - theCrosswordTop;
    
    insert_code("_sender.php?fun=scandy_question&x="+x+"&y="+y+"&crossword_id="+crosswordId, 'questions', 'showArrow('+x+', '+y+', \'\', false, 3);');
    
    showLoading('questions');
    
    $('questions').style.left = (left + 34)+"px";
    $('questions').style.top = (top + 24)+"px";
    
    showObj('questions');
    showQuestionCheck = false;
}

function hideQuestions(){
    if(!showQuestionCheck) {
        hideObj('questions');
        
        hideObj('horizontal_str');
        hideObj('horizontal_brk');
        hideObj('vertical_str');
        hideObj('vertical_brk');
        
        var selectedQuestion = $(lastSelectedQuestion);
        if(selectedQuestion != null)
            selectedQuestion.className = "black_box";
        showQuestionCheck = true;
    }
}

function showArrow(x, y, direction, inv, key){
    var boxId = document.getElementById("black_box_"+x+"_"+y);//"letter_"+x+"_"+y
    var questions_type = $('questions_type').value.split("|");
    
    // взима позицията на контеинера на кръстословицата
    theCrosswordPosition = findPos($("the_crossword"));
    theCrosswordLeft = theCrosswordPosition[0];
    theCrosswordTop = theCrosswordPosition[1];
    
    // взима позицията на самия въпрос
    boxLocation = findPos(boxId);
    boxLocation[0] = boxLocation[0] - theCrosswordPosition[0];
    boxLocation[1] = boxLocation[1] - theCrosswordPosition[1];
    
    // показва първоначалните срелки
    if(key == 3) {
        if(questions_type[0] == 'vertical_str' || questions_type[1] == 'vertical_str') {
            $('img_vertical_str').src = "../interface/vertical_str_arrow.png";
            $('vertical_str_Id').src = "../interface/vertical_str_arrow.png";
            
            $('vertical_str').style.left = (boxLocation[0]+11)+"px";
            $('vertical_str').style.top = (boxLocation[1]+29)+"px";
            showObj('vertical_str');
        }
        if(questions_type[0] == 'horizontal_brk' || questions_type[1] == 'horizontal_brk') {
            $('img_horizontal_brk').src = "../interface/horizontal_brk_arrow.png";
            $('horizontal_brk_Id').src = "../interface/horizontal_brk_arrow.png";
            
            $('horizontal_brk').style.left = (boxLocation[0]+11)+"px";
            $('horizontal_brk').style.top = (boxLocation[1]+29)+"px";
            showObj('horizontal_brk');
        }
        if(questions_type[0] == 'horizontal_str' || questions_type[1] == 'horizontal_str') {
            $('img_horizontal_str').src = "../interface/horizontal_str_arrow.png";
            $('horizontal_str_Id').src = "../interface/horizontal_str_arrow.png";
            
            $('horizontal_str').style.left = (boxLocation[0]+44)+"px";
            $('horizontal_str').style.top = (boxLocation[1]-4)+"px";
            showObj('horizontal_str');
        }
        if(questions_type[0] == 'vertical_brk' || questions_type[1] == 'vertical_brk') {
            $('img_vertical_brk').src = "../interface/vertical_brk_arrow.png";
            $('vertical_brk_Id').src = "../interface/vertical_brk_arrow.png";
            
            $('vertical_brk').style.left = (boxLocation[0]+44)+"px";
            $('vertical_brk').style.top = (boxLocation[1]-4)+"px";
            showObj('vertical_brk');
        }
    } else {
        if(inv) {
            $('img_'+direction).src = "../interface/"+direction+"_arrow_s.png";
            $(direction+'_Id').src = "../interface/"+direction+"_arrow_s.png";
        } else {
            $('img_'+direction).src = "../interface/"+direction+"_arrow.png";
            $(direction+'_Id').src = "../interface/"+direction+"_arrow.png";
        }
    }   
}

function selectQuestion(question, x, y, direction, event) {
    if(question == '') return;
    
    $('question_shown').innerHTML = question+'?';
    
    switch(direction){
        case 'vertical_str':
            changeDirection('vertical');
            letterId = "letter_"+x+"_"+(y + 1);
            break;
        case 'horizontal_brk':
            changeDirection('horizontal');
            letterId = "letter_"+x+"_"+(y + 1);
            break;
        case 'horizontal_str':
            changeDirection('horizontal');
            letterId = "letter_"+(x + 1)+"_"+y;
            break;
        case 'vertical_brk':
            changeDirection('vertical');
            letterId = "letter_"+(x + 1)+"_"+y;
            break;
    }
    
    // избира квадратчето в което да започне да се пише отговора
    var boxId = $(letterId);
    
    if(boxId.value != '')
        selectBox(boxId, true, event);
    else selectBox(boxId, false, event);
    //selectBox(boxId);
}

function selectBox(boxId, next, event){
    var letters = boxId.id.split("_");
    var l_x = letters[1];
    var l_y = letters[2];
    
    // опит да се ограничат само българските букви, но проверката нещо не работи
    symbol = $("letter_"+l_x+"_"+l_y);
    symbol.value = symbol.value.toUpperCase();
    
    if(!in_array($('letter_'+l_x+'_'+l_y).value, alphabeta) && next) {
        if(event.keyCode == 8) {
            if(directionWriting == "horizontal") {
                bs_x = l_x - 1;
                bs_y = l_y;
            } else {
                bs_x = l_x;
                bs_y = l_y - 1;
            }
            
            if($('letter_'+bs_x+'_'+bs_y) != null) {
                $('letter_'+bs_x+'_'+bs_y).style.background = "#F0FF00";
                $('letter_'+bs_x+'_'+bs_y).select();
                $('letter_'+bs_x+'_'+bs_y).focus();
                lastTypedBox = 'letter_'+bs_x+'_'+bs_y;
            } else {
                $('letter_'+l_x+'_'+l_y).focus();
                $('letter_'+l_x+'_'+l_y).style.background = "#F0FF00";
            }
        }
        $('letter_'+l_x+'_'+l_y).value = "";
        
        insert_code('_sender.php?fun=scandy_save_letter&x='+l_x+'&y='+l_y+'&letter='+$('letter_'+l_x+'_'+l_y).value);
        
        return;
    }

    if(next) {
        var x = 1;
        var xLength = 1;
        var y = 1;
        var yLength = 1;
            
        // отброява колко букви са попълнени
        if(directionWriting == "horizontal") {
            // избира да пропуска написаните букви и направо да отива на първото свободно квадратче
            while($("letter_"+(l_x * 1 + xLength)+"_"+l_y) != null) xLength++;
                xLength--;
            
            while(xLength > 0) {
                if($("letter_"+(l_x * 1 + x)+"_"+l_y).value != '')
                    x++;
                xLength--;
            }
            
            nextSelectedBox = "letter_"+(l_x * 1 + x)+"_"+l_y;
        } else {
            // избира да пропуска написаните букви и направо да отива на първото свободно квадратче
            while($("letter_"+l_x+"_"+(l_y * 1 + yLength)) != null) yLength++;
                yLength--;
            while(yLength > 0) {
                if($("letter_"+l_x+"_"+(l_y * 1 + y)).value != '')
                    y++;
                yLength--;
            }
            
            nextSelectedBox = "letter_"+l_x+"_"+(l_y * 1 + y);
        }
    } else
        nextSelectedBox = "letter_"+l_x+"_"+l_y;
    
//    checkCrossword();
    
    if(lastTypedBox != '') {
        // връща белия цвят на квадратчето в което е поставена буква
        $(lastTypedBox).style.background = "#FFFFFF";
        $(lastTypedBox).blur();
    }
    
    // оцветява квадратчето в което ще се пише в жълто
    if($(nextSelectedBox) != null) {
        $(nextSelectedBox).style.background = "#F0FF00";
        $(nextSelectedBox).focus();
        if($(nextSelectedBox).value != '')
            $(nextSelectedBox).select();
        lastTypedBox = nextSelectedBox;
    } else
        lastTypedBox = '';
    
    if(rightMenuVisible != '')
        hideObj('right_menu');
        
    insert_code('_sender.php?fun=scandy_save_letter&x='+l_x+'&y='+l_y+'&letter='+$('letter_'+l_x+'_'+l_y).value);
}

function onBoxClick(event, input){
    hideQuestions();
    
    if(lastTypedBox != '') {
        // връща белия цвят на квадратчето в което е поставена буква
        var lastBox = document.getElementById(lastTypedBox);
        lastBox.style.background = "#FFFFFF";
    }
    lastTypedBox = input;
    
    var inputId = document.getElementById(input);
    inputId.style.background = "#F0FF00";
    
    if(event.which == 3){
        var rightMenu = document.getElementById("right_menu");
        rightMenu.style.top = (event.clientY + document.body.scrollLeft - 90)+"px";//event.clientX;
        rightMenu.style.left = (event.clientX + document.body.scrollTop - 220)+"px";//event.clientY;
        showObj("right_menu");
        rightMenuVisible = input;
    }
}

function clearBox(clearBoxId) {
    clearBoxId.style.background = "#FFFFFF";
}

// записва попълнените полета от потребителя на сканди кръстословицата
function saveCrossword(period, user_save, firstTime) {
    if(firstTime)
        insert_code('_sender.php?fun=scandy_save&autosave');
        
    clearTimeout(savedTimerTimeoutId);
    startSavedTimer(0);
    
    // period е времето в минути
    if(!user_save)
        setTimeout("saveCrossword("+period+", "+user_save+", true)", period * 60 * 1000);
}

// стартира брояча, който отброява колко време е минало от последното запазване на решението
var savedTimerTimeoutId = 0;
function startSavedTimer(seconds) {
    if($('saved_timer') != null) {
        var min = Math.floor(seconds / 60);
        var secs = Math.round(seconds % 60);
        
        if(secs < 10) secs = '0'+secs;
        
        $('saved_timer').innerHTML = min+':'+secs;
        
        seconds = seconds + 1;
        
        savedTimerTimeoutId = setTimeout("startSavedTimer("+seconds+")", 1000);
    }
}

// променя посоката на изписване в сканди кръстословицата
function changeDirection(auto) {
    var imgSrc1 = 'interface/double_arrow_vertical.png';
    var imgSrc2 = 'interface/double_arrow_horizontal.png';
    var img = 'direction_switch';
    
    // при положение, че функцията е извикана да смени посоката без значение от настоящата посока
    if(auto == null) {
        if(directionWriting == "vertical") setDirection = "horizontal";
        else setDirection = "vertical";
    // при положение, че посоката трябва да бъде сменена в точно определена такава
    } else {
        if(auto == 'horizontal') setDirection = "horizontal";
        else setDirection = "vertical";
    }
    
    if(setDirection == 'horizontal') {
        directionWriting = "horizontal";
        $(img).src = imgSrc2;
        $('write_direction').innerHTML = "хоризонтално";
    } else {
        directionWriting = "vertical";
        $(img).src  = imgSrc1;
        $('write_direction').innerHTML = "вертикално";
    }
    
    if(lastTypedBox != '') {
        $(lastTypedBox).style.background = "#F0FF00";
        $(lastTypedBox).focus();
    }
}

// променя стила на дума от hint-овете
function changeHints(strongId) {
    if($(strongId).style.textDecoration == 'line-through')
        $(strongId).style.textDecoration = 'none';
    else
        $(strongId).style.textDecoration = 'line-through';
}

// взима подксазка за сканди кръстословицата
function scandyTip() {
    parts = $('tip').innerHTML.split("|");
    answer = parts[0];
    direction = parts[1];
    x = parts[2];
    y = parts[3];
    question = parts[4];
    
    $('question_shown').innerHTML = question+'?';
    
    if(direction == 'horizontal') changeDirection('horizontal');
    else changeDirection('vertical');
    
    writeScandyTip(answer, 0, direction, x, y);
}

// изписва подсказката в сканди кръстословицата
function writeScandyTip(answer, pos, direction, x, y) {
    pos = parseInt(pos);
    x = parseInt(x);
    y = parseInt(y);
    
    if(pos < answer.length) {
        // отбелязва с жълто квадратчето в което ще пише
        $('letter_'+x+'_'+y).focus();
        $('letter_'+x+'_'+y).blur();
        $('letter_'+x+'_'+y).style.background = '#F0FF00';
        // отбелязва с червен фон квадратчето в което буквата която е била написана не е правилна
        if($('letter_'+x+'_'+y).value != '')
            if($('letter_'+x+'_'+y).value != answer[pos])
                $('letter_'+x+'_'+y).style.background = '#FF0000';
        // записва самата буква в крадратчето
        $('letter_'+x+'_'+y).value = answer[pos];
        // връща белия фон на квадратчето в което вече е написана буква
        if(pos)
            if($('letter_'+p_x+'_'+p_y).style.background != '#FF0000')
                $('letter_'+p_x+'_'+p_y).style.background = '#FFFFFF';
                
        insert_code('_sender.php?fun=scandy_save_letter&x='+x+'&y='+y+'&letter='+answer[pos]);
            
        if(direction == 'vertical') {
            y = y + 1;
            p_y = y - 1;
            p_x = x;
        } else {
            x = x + 1;
            p_y = y;
            p_x = x - 1;
        }
        
        pos = pos + 1;
        
        setTimeout("writeScandyTip('"+answer+"', "+pos+", '"+direction+"', "+x+", "+y+");", 500);
    } else
        // връща белия фон на квадратчето в което вече е написана буква в края на думата
        if($('letter_'+p_x+'_'+p_y).style.background != '#FF0000')
            $('letter_'+p_x+'_'+p_y).style.background = '#FFFFFF';  
}
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////
// SUDOKU
//////////////////////////////////////////////////////////////////

var selectedNumberBox = '';
function selectNumberBox(boxId, e) {
    boxId.className = 'bk_yellow';
    showRightMenu(e);
    selectedNumberBox = boxId;
    boxId.select();
}

function deselectNumberBox(boxId) {
    boxId.className = '';
    rightMenuTimeoutId = setTimeout('hideObj(\'right_menu\');', 150);
}

function inputNumber(number, completed) {
    selectedNumberBox.value = number;
    selectedNumberBox.blur();
    hideObj('right_menu');
    
    if(completed == 'no')
        sudokuSolved();
}

function saveSudoku(period, firstTime, oneTime) {
    if(firstTime) {
        if($('frm_sudoku_grid') != null) {
            $('frm_sudoku_grid').action = '_sender.php?fun=sudoku_save'; 
            sendRequest($('frm_sudoku_grid'));
        }
    }
    
    // period е времето в минути
    if($('frm_sudoku_grid') != null && !oneTime)
        setTimeout("saveSudoku("+period+", true)", period * 60 * 1000);
}

function sudokuCheck() {
    if($('sudoku_check').value != '')
        if(parseInt($('sudoku_check').value) > 0) {
            if(parseInt($('sudoku_check').value) > 1)
                alert('Имате '+$('sudoku_check').value+' грешки! Оцветените цифри са сгрешени.');
            else
                alert('Имате '+$('sudoku_check').value+' грешка! Оцветените цифри са сгрешени.');
        } else
            alert('Няма сгрешени цифри в решението до този момент!');
}

//function removeSudokuTips() {
//    var tips = $('sudoku_tips').lang;
//    tips = tips - 1;
//    $('sudoku_tips').lang = tips;
//    $('sudoku_tips').innerHTML = '('+tips+')';
//}

var clockTimerId = 0;
var sudokuDifficulties = Array(Array(1200, 900, 600), Array(1020, 720, 480), Array(840, 540, 300));

function startClock(diff) {
    clearTimeout(clockTimerId);
    setTimeout('runningClock(0, "'+diff+'")', 1000);
}

function runningClock(seconds, diff) {
    var min = Math.floor(seconds / 60);
    var secs = Math.round(seconds % 60);
    var new_style = ' green';
    
    // определя кое ниво е судокуто
    if(diff == 'hard') diff = 2;
    if(diff == 'normal') diff = 1;
    if(diff == 'easy') diff = 0;
    
    // определя дали трябва да се смени цвета на таймера
    if(diff != 'undefined') {
        if(seconds >= sudokuDifficulties[diff][2])
            new_style = ' yellow';
        if(seconds >= sudokuDifficulties[diff][1])
            new_style = ' red';
        if(seconds >= sudokuDifficulties[diff][0])
            new_style = ' black';
    }
    
    if(secs < 10) secs = '0'+secs;
    
    if($('timer') != null) {
        $('timer').innerHTML = min+':'+secs;
        $('timer').className = 'timer'+new_style;
    }
    
    seconds = seconds + 1;
    clockTimerId = setTimeout('runningClock('+seconds+', "'+diff+'")', 1000);
}

function restartSudoku() {
    var restarts = $('sudoku_restarts').lang;
    
    restarts = parseInt(restarts) + 1;
    
    switch(restarts) {
        case 1:
            alert('При рестартиране на судокуто, точките които ще получиш при неговото успешно решаване, са половината от точките, които би получил при нормално решаване!');
            break;
        case 2:
            alert('При рестартиране на судокуто, точките които ще получиш при неговото успешно решаване, са една четвърт от точките, които би получил при нормално решаване!');
            break;
        default:
            alert('След третото рестартиране на судокуто, не се получават точки за решаването му!');
            break;
    }
    
    //$('sudoku_restarts').innerHTML = '('+restarts+')';
    $('sudoku_restarts').lang = restarts;
}

function sudokuSolved() {
    maxX = 9;
    maxY = 9;
    
    for(i = 1; i <= maxX; i++)
        for(j = 1; j <= maxY; j++) {
            if(!is_number($('cell_'+i+'_'+j).value))
                return;
        }
    
    alert('saving sudoku as solved...');
    $('frm_sudoku_grid').action = '_sender.php?fun=sudoku_user_solve'; 
    sendRequest($('frm_sudoku_grid'), 'sudoku_grid');
}

//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////
// RIGHT MENU
//////////////////////////////////////////////////////////////////

var rightMenuTimeoutId;
function showRightMenu(mouse){
    if(mouse.button == 2) {
        clearTimeout(rightMenuTimeoutId);
        scrolledPos = getScrolledPosition();
        showObj('right_menu');
        $('right_menu').style.top = (mouse.clientY + scrolledPos[1] - 5)+"px";
        $('right_menu').style.left = (mouse.clientX + scrolledPos[0] - 5)+"px";
    }
}

//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////
// USERS
//////////////////////////////////////////////////////////////////

var colorTimeoutId = 0;

function colorPreview(color) {
    clearTimeout(colorTimeoutId);
    
    $('color_tester').style.background = '#'+color;
}

function colorChange(color) {
    if(color) {
        $('color_tester').style.background = '#'+color;
        $('user_name').style.color = '#'+color;
        $('color_tester').lang = color;
    } else
        $('color_tester').style.background = '#'+$('color_tester').lang;
}

function changeIcon(icon_id, icon) {
    if($('user_icon_'+$('user_panel').lang) != null)
        $('user_icon_'+$('user_panel').lang).className = '';
    $('user_icon_'+icon_id).className = 'sel';
    
    $('user_icon_img').src = 'draw.php?path=avatars/icons/'+icon+'&do=fixed&w=40&h=40';
}

function activateRegistrationForm() {
    var emailPattern = /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
    
    if($('username').value != '')
        if(emailPattern.test($('email').value))
            if($('password').value != '')
                if($('password').value == $('password_again').value)
                    $('sbmt_frm').submit();
}

function activateForgottenPassForm() {
    var emailPattern = /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
    
    if(emailPattern.test($('email').value) || $('username').value != '')
        $('fgtn_pswd_frm').submit();
}

function checkRegistrationUsername() {
    if($('username').value != '')
        insert_code('_sender.php?user=check&what=name&value='+$('username').value, 'mark_username');
}

function checkForgottenPassUsername() {
    if($('username').value != '')
        insert_code('_sender.php?user=check&what=name_fp&value='+$('username').value, 'mark_username');
}

function checkRegistrationPassword() {
    if($('password').value != '')
        $('mark_password').innerHTML = '<img src="interface/bk_user_mark_yes.png" />';
    else
        $('mark_password').innerHTML = '<img src="interface/bk_user_mark_no.png" />';
}

function checkRegistrationPasswords() {
    if($('password_again').value != '' && $('password').value == $('password_again').value)
        $('mark_password_again').innerHTML = '<img src="interface/bk_user_mark_yes.png" />';
    else
        $('mark_password_again').innerHTML = '<img src="interface/bk_user_mark_no.png" />';
}

//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////
// ARCHIVE
//////////////////////////////////////////////////////////////////

function changeArchiveYear(newYear) {
    $('archive_year').value = newYear;
    sendRequest($('frm_change_arch_year'), '', 'location.reload();');
}

//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////
// ADMIN CROSSWORDS
//////////////////////////////////////////////////////////////////
function nextLetter(maxX, maxY, x, y, event) {
    querstionMark = "?";
    $('field_'+x+'_'+y).value = $('field_'+x+'_'+y).value.toUpperCase();
    
    checkArr = new Array("А", "Б", "В", "Г", "Д", "Е", "Ж", "З", "И", "Й", "К", "Л", "М", "Н", "О",
                         "П", "Р", "С", "Т", "У", "Ф", "Х", "Ц", "Ч", "Ш", "Щ", "Ъ", "Ь", "Ю", "Я",
						 "!");
	
    if(!in_array($('field_'+x+'_'+y).value, checkArr)) {
        if($('field_'+x+'_'+y).value == querstionMark) {
            showLoading('question');
            
            $('field_'+x+'_'+y).className = "bk_black";
            $('field_'+x+'_'+y).type = "button";
            $('field_'+x+'_'+y).onblur = function() {};
            $('field_'+x+'_'+y).value = querstionMark;
            $('field_'+x+'_'+y).onclick = function() {insert_code('_sender.php?fun=edit_question&x='+x+'&y='+y, 'question');};
            $('field_'+x+'_'+y).blur();
            $('field_'+x+'_'+y).id = "question_"+x+"_"+y;
			
            insert_code("_sender.php?fun=new_questions&x="+x+"&y="+y, "question", "$('question_text').focus();");
			return;
		} else {
			if(event.keyCode == 8) {
				if(x > 0) {
					bs_x = x - 1;
					bs_y = y;
				} else {
					if(y > 0) {
						bs_x = maxX - 1;
						bs_y = y - 1;
					} else {
						return;
					}
				}
				$('field_'+x+'_'+y).blur();
				if($('field_'+bs_x+'_'+bs_y) != null) {
					$('field_'+bs_x+'_'+bs_y).className = "bk_yellow";
					$('field_'+bs_x+'_'+bs_y).select();
					$('field_'+bs_x+'_'+bs_y).focus();
				} else {
					$('field_'+x+'_'+y).focus();
					$('field_'+x+'_'+y).className = "bk_yellow";
				}
			}
			$('field_'+x+'_'+y).value = "";
            
            if($('field_'+x+'_'+y).value != null)
                insert_code("_sender.php?fun=save_letter&letter="+$('field_'+x+'_'+y).value+"&x="+x+"&y="+y, "question"); // , "$('question_text').focus();"
            return;
    }
    }
	
	if(x < (maxX - 1)) {
		if($('field_'+(x+1)+'_'+y) != null) {
			$('field_'+(x+1)+'_'+y).className = "bk_yellow";
			$('field_'+(x+1)+'_'+y).select();
			$('field_'+(x+1)+'_'+y).focus();
		} else {
			$('field_'+x+'_'+y).blur();
		}
	} else {
		if(y <= (maxY -1)) {
			if($('field_0_'+(y+1)) != null) {
				$('field_0_'+(y+1)).className = "bk_yellow";
				$('field_0_'+(y+1)).select();
				$('field_0_'+(y+1)).focus();
			} else {
				$('field_'+x+'_'+y).blur();
				$('hints').focus();
			}
		} else {
			$('hints').focus();
		}
	}
	
	if($('field_'+x+'_'+y).value != null)
            insert_code("_sender.php?fun=save_letter&letter="+$('field_'+x+'_'+y).value+"&x="+x+"&y="+y, "question"); // , "$('question_text').focus();"
}

function saveQuestion(maxX, maxY, x, y) {
	var nextLetter = false;
	
	if($('question_text').value == '') {
		alert("Не може да въведеш празен върпос!");
		$('question_text').focus();
		return;
	}
	
	if($('question_num').value < 2) {
		if(confirm("Ще записваш ли втори въпрос?")) {
			sendRequest($('frm_question'), 'question', 'insert_code(\'_sender.php?fun=new_questions&x='+x+'&y='+y+'\', \'question\', \'$(\\\'question_text\\\').focus();\');');
			showLoading('question');
		} else {
			sendRequest($('frm_question'), 'question');
			nextLetter = true;
		}
		
		$('question_'+x+'_'+y).value = '';
	} else {
		sendRequest($('frm_question'), 'question');
		nextLetter = true;
	}
	
	if(nextLetter) {
		if(x < (maxX - 1)) {
			if($('field_'+(x+1)+'_'+y) != null) {
				$('field_'+(x+1)+'_'+y).className = "bk_yellow";
				$('field_'+(x+1)+'_'+y).select();
				$('field_'+(x+1)+'_'+y).focus();
			} else {
				$('field_'+x+'_'+y).blur();
			}
		} else {
			if(y < (maxY -1)) {
				if($('field_0_'+(y+1)) != null) {
					$('field_0_'+(y+1)).className = "bk_yellow";
					$('field_0_'+(y+1)).select();
					$('field_0_'+(y+1)).focus();
				} else {
					$('field_'+x+'_'+y).blur();
				}
			} else {
				$('field_'+x+'_'+y).blur();
			}
		}
	}
}

function updateQuestion() {
    if($('exist_question_0') != null)
	if($('question_text_'+$('exist_question_0').value).value == '') {
	    alert("Първият въпрос е празен! Не може да запишеш празен върпос!");
	    return;
	}
	    
    if($('exist_question_1') != null) {
	if($('question_text_'+$('exist_question_1').value).value == '') {
	    alert("Вторият въпрос е празен! Не може да запишеш празен върпос!");
	    return;
	}
    }
    
    sendRequest($('frm_question'), 'question');
}

function deleteQuestion(x, y, question) {
    if(confirm("Сигурен ли си, че искаш да изтриеш този въпрос - '"+question+"?' ?")) {
        insert_code("_sender.php?fun=delete_question&id="+$('id').value);
        
        $('question_num').value = parseInt($('question_num').value) - 1;
        
        cancelNewQuestion(x, y);
    } else
        $('question_text').focus();
}

function cancelNewQuestion(x, y) {
    question_num = $('question_num').value;
    $('question').innerHTML = '';
    
    if(question_num == 0) {
        $('question_'+x+'_'+y).className = "bk_yellow";
        $('question_'+x+'_'+y).type = "text";
        $('question_'+x+'_'+y).value = "";
        $('question_'+x+'_'+y).onblur = function() {if(this.value != '?') this.className = '';};
        $('question_'+x+'_'+y).onclick = function() {this.select(); this.className = 'bk_yellow';};
        $('question_'+x+'_'+y).id = "field_"+x+"_"+y;
        
        $('field_'+x+'_'+y).focus();
    }
}

function saveCross(maxX, maxY) {
    if($('title').value == '') {
        alert("Не си попълнил заглавието на кръстословицата! Не може кръстословицата да няма заглавие!");
        return;
    }
    
    for(i = 0; i < maxY; i++)
	for(j = 0; j < maxX; j++) {
	    if($('field_'+j+'_'+i) != null && $('field_'+j+'_'+i).value == '') {
		alert("Има непопълнени полета! За да може да запишеш кръстословицата, не трябва да има празни полета.");
		$('field_'+j+'_'+i).className = "bk_yellow";
		$('field_'+j+'_'+i).focus();
		return;
	    }
	}
	
    if($('hints').value == '') {
	if(!confirm("Сигурен ли си, че няма подсказващи думи към тази кръстословица?"))
	return;
    }
	
    $('frm_new_cross').submit();
}

function in_array(value, arr){
    for(var i = 0; i < arr.length; i++)
        if(value == arr[i])
            return true;
    
    return false;
}

function saveHoroscope(key) {
	horoscopeText = $('text_'+key).value;
	
    if(key == 11)
        sendRequest($('sign_'+key), 'control_'+key, 'location.reload();');
    else
        sendRequest($('sign_'+key), 'control_'+key);
	
	showLoading('form_cont_'+key);
	$('form_cont_'+key).innerHTML = horoscopeText;
}
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////
// SUDOKU
//////////////////////////////////////////////////////////////////
function nextNumber(bar, number_x, number_y, event, int_value) {
    checkArr = new Array(1, 2, 3, 4, 5, 6, 7, 8, 9);
	
	var maxX = 2;
	var maxY = 2;
	var maxBar = 10;
    var x = number_x;
    var y = number_y;
    var bar_ = bar;
	
    if(!in_array(int_value, checkArr)) {
		if(event.keyCode == 8) {
			if(number_x > 0) {
				bs_x = number_x - 1;
				bs_y = number_y;
			} else {
				if(number_y > 0) {
					bs_x = maxX - 1;
					bs_y = y - 1;
				} else {
					return;
				}
			}
			/*$('field_'+x+'_'+y).blur();
			if($('field_'+bs_x+'_'+bs_y) != null) {
				$('field_'+bs_x+'_'+bs_y).className = "bk_yellow";
				$('field_'+bs_x+'_'+bs_y).select();
				$('field_'+bs_x+'_'+bs_y).focus();
			} else {
				$('field_'+x+'_'+y).focus();
				$('field_'+x+'_'+y).className = "bk_yellow";
			}*/
		}
		$('bar_'+bar+'_'+number_x+'_'+number_y).value = "";
		
		insert_code("_sender.php?fun=save_sudoku_number&number="+int_value+"&bar="+bar_+"&x="+y+"&y="+x, "");
		return;
    }
    
    if(number_x < maxX) {
        number_x = number_x + 1;
    } else {
		number_x = 0;
        if(number_y < maxY) {
            number_y = number_y + 1;
        } else {
            number_y = 0;
            bar = bar + 1;
        }
    }
    
    if(bar < maxBar) {
        if($('bar_'+bar+'_'+number_x+'_'+number_y) != null) {
            $('bar_'+bar+'_'+number_x+'_'+number_y).className = "bk_yellow";
            $('bar_'+bar+'_'+number_x+'_'+number_y).select();
            $('bar_'+bar+'_'+number_x+'_'+number_y).focus();
        }
    } else
        $('bar_'+bar_+'_'+x+'_'+y).blur();
    
    insert_code("_sender.php?fun=save_sudoku_number&number="+int_value+"&bar="+bar_+"&x="+y+"&y="+x, "");
}
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////