// JavaScript Document
var m_sSudoku;
var m_sSudokuInit;
var xmlhttp;
var m_selectedCell;
var m_selectedCellColor;
var m_phpPath = '/sudoku/';
var m_Solved;
var m_gameStarted;

var m_arBackgroundColors;
var m_arProblemCells;

var m_lastCell;
var m_updateCell;
var m_x;
var m_y;
var m_sLevel;
var m_iLevel;
var m_iReveals;

var m_presetFontColor = '#444444'
var m_activeCellBackgroundColor= '#eeeeee';
var m_wrongCellBackgroundColor= '#ff0000';

//timer variables
var m_tStarted;
var m_tObject;
var m_tSecs;
var m_tMins;

//scoring
var m_scBase1 = 240;
var m_scBase2 = 480;
var m_scBase3 = 720;
var m_scBase4 = 960;
var m_scBase5 = 1200;
var m_scRevPen = 10;
var m_scRevPenInc = 5;

///////////////////////
// startup functions //
///////////////////////
function on_start()
{
	document.getElementById("btnPause").disabled = true;
	document.getElementById("btnFinish").disabled = true;
	document.getElementById("txtUserName").style.visibility = "hidden";
	document.getElementById("btnSave").style.visibility = "hidden";

}

//////////////////////
// sudoku functions //
//////////////////////
function finished_sudoku()
{
	if (m_Solved==true) 
	{
		alert("Yes, you did it! Try a new or even harder one!");
		return;
	}
	m_sSudoku = read_grid();
	htmlIsSolved();
	//clear_grid();
}

function solve_sudoku()
{
	if(!m_sSudoku) return;
	
	if(confirm("Solve the puzzle for you?"))
		htmlGetSolveSudoko();
}

function create_new()
{
	var e = document.getElementById("txtLevel");
	m_iLevel = e.value;
	switch(m_iLevel){
		case "3" : m_sLevel = "Difficult";break;
		case "2" : m_sLevel = "Standard";break;
		case "1" : m_sLevel = "Easy";break;
	}
	e = document.getElementById("btnNew");
	e.disabled = true;
	resetOriginalBackgroundColors();
	readBackgroundColors();
	htmlGetNewSudoko(m_iLevel);	
}

function reveal_cell()
{
	if(!m_selectedCell) return;
	htmlGetRevealCell();
}

//////////////////////
//  Grid functions  //
//////////////////////
function update_grid(sSudoku)
{
	var x, y, val;
	var e, sElement, iTab = 1;
	
	for (var i = 0; i < 16; i++)
    {
    	x = parseInt(i % 4) + 1;
        y = parseInt(i / 4) + 1;
        val = sSudoku.substring(i, i + 1);
        sElement = "txtC" + x + y;
        e = document.getElementById(sElement);
        remove_event(e,"change",check_cell);
		remove_event(e,"blur",cell_leave);
		remove_event(e,"focus",cell_enter);
        add_event(e,"change",check_cell);
		add_event(e,"blur",cell_leave);
		add_event(e,"focus",cell_enter);
		if (val != 0)
        {
           e.value = val;
		   setReadOnly(e);
		   e.style.color = "#666666";
		}
        else
        {
        	e.value = "";
			removeReadOnly(e);
			e.style.color = "#000000";
        }
    }
    for (var x = 1; x <= 4; x++)
    {
    	for (var y = 1; y <= 4; y++)
    	{
    		sElement = "txtC" + y + x;
	        e = document.getElementById(sElement);
	        val = e.value;
	        if (val=="")
	        {
	        	e.tabIndex = iTab;
	        	iTab++;
	        }
    	}
    }
}
function read_grid()
{
	var x, y, val;
	var e, sElement, sSudoku = "";
	
	for (var i = 0; i < 16; i++)
    {
    	x = parseInt(i % 4) + 1;
        y = parseInt(i / 4) + 1;
        sElement = "txtC" + x + y;
        e = document.getElementById(sElement);
        val = e.value;
        if (val=="") {
        	val = "0"; 
        }
        sSudoku += '' + e.value;
    }
    return(sSudoku);
}
function clear_grid()
{
	var x, y, val;
	var e, sElement;
	
	for (var i = 0; i < 16; i++)
    {
    	x = parseInt(i % 4) + 1;
        y = parseInt(i / 4) + 1;
        sElement = "txtC" + x + y;
        e = document.getElementById(sElement);
		e.value = "";
	}
}

////////////////////////////
//  validation functions  //
////////////////////////////
function check_cell(e)
{
	var element = find_target(e);
	var val = element.value;
	if(val<1 || val>4 || isNaN(val)) { 
		if(val.length > 1) { //if more numbers, then possibilities.
			element.className += " valueOptions";
			element.style.color = "#FF0000";
			val = 0;
		}
		//return 0;
	} else {
		if(element.className.indexOf("valueOptions")) { 
			element.className = element.className.replace(/ valueOptions/g,"");
			element.style.color = "#000";
		}
	}
	m_updateCell = m_selectedCell;
	//htmlSetCell(val);
}


function cell_enter(e)
{
	m_selectedCell = find_target(e);
	var strID = m_selectedCell.id.substr(4,5);
	var asTmp = strID.split("");  
	var currBackgroundColor = m_selectedCell.style.background.toLowerCase();
	m_x = parseInt(asTmp[0]) - 1;
	m_y = parseInt(asTmp[1]) - 1;
	if (currBackgroundColor != m_wrongCellBackgroundColor && !m_selectedCell.readOnly){
		m_selectedCellColor = m_selectedCell.style.background.toLowerCase();
		m_selectedCell.style.background = m_activeCellBackgroundColor;
	}
	m_lastCellClass = m_selectedCell.className;
	m_lastCell = m_selectedCell;
	
}

function cell_leave(e)
{
	if (!m_lastCell) {
		m_lastCell = e;
		alert("und.");
	}
	//alert(m_lastCell.id);
	if (isProblemCell(m_lastCell.id))
	{
		m_lastCell.style.background = m_wrongCellBackgroundColor;
	} else {
		removeProblemCell(m_lastCell.id);
		setOriginalBackgroundColor(m_lastCell.id);		
	}
}

/////////////////////////////
//  php receive functions  //
/////////////////////////////

//get new sudoku
function htmlGetNewSudoko(iLevel)
{
    var url = m_phpPath + 'new_sudokuKid4.php';

    if (window.ActiveXObject) {              // for IE
         xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
         }
    else if (window.XMLHttpRequest) {   // for other browsers{
         xmlhttp=new XMLHttpRequest();
    }

    xmlhttp.onreadystatechange=xmlhttpAswer_New;
    xmlhttp.open("POST",url,true);
	
    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlhttp.send('level=' + iLevel);

}
function xmlhttpAswer_New()
{
	if (xmlhttp.readyState == 4)
    {
        if(xmlhttp.status == 200)
        {
        	
			var newSudoku = xmlhttp.responseText;
			m_sSudoku = newSudoku;
			m_sSudokuInit = newSudoku;
			update_grid(newSudoku);
			document.getElementById("btnNew").disabled = false;
		    document.getElementById("btnPause").disabled = false;
		    document.getElementById("btnFinish").disabled = false;
		    
		    //start timer.
			timer_stop();
			m_tSecs = 0;
			timer_start();
			m_tStarted = 1;
			m_iReveals = 0;
			m_Solved = false;
			m_gameStarted = true;
        }
        else
        {
            alert("Error loading page\n"+ xmlhttp.status +":"+ xmlhttp.statusText);
        }
    }
}

//try to set value to cell, if possible
function htmlSetCell(val)
{
    var url = m_phpPath + 'set_itemKid4.php';
    var frm;

    if (window.ActiveXObject) {              // for IE
         xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
         }
    else if (window.XMLHttpRequest) {   // for other browsers{
         xmlhttp=new XMLHttpRequest();
    }
    m_lastCell = m_selectedCell;
    xmlhttp.onreadystatechange=xmlhttpAswer_SetCell;
    xmlhttp.open("POST",url,true);

    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    var params = 'sudoku=' + m_sSudoku + '&x=' + m_x + '&y=' + m_y + '&val=' + val;
    xmlhttp.send(params);

}
function xmlhttpAswer_SetCell()
{
	if (xmlhttp.readyState == 4)
    {
        if(xmlhttp.status == 200)
        {
           var anser = xmlhttp.responseText;
           var tmp = anser.split(";");
           var val = m_updateCell.value;
           var res = tmp[0];
           m_sSudoku = tmp[1];
           if (res == 0 && val > 0 && val < 10){
           		addProblemCell(m_updateCell);
		   }else{
		   		removeProblemCell(m_updateCell.id);
           	  	setOriginalBackgroundColor(m_updateCell.id);           	  	
		   }
        }
        else
        {
            alert("Error loading page\n"+ xmlhttp.status +":"+ xmlhttp.statusText);
        }
    }
}

//check, whether puzzle has been solved
function htmlIsSolved()
{
    var url = m_phpPath + 'solvedKid4.php';
    
    var frm;

    if (window.ActiveXObject) {              // for IE
         xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
         }
    else if (window.XMLHttpRequest) {   // for other browsers{
         xmlhttp=new XMLHttpRequest();
    }
    
    xmlhttp.onreadystatechange=xmlhttpAswer_IsSolved;
    xmlhttp.open("POST",url,true);

    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    var params = 'sudoku=' + m_sSudoku;
    xmlhttp.send(params);

}
function xmlhttpAswer_IsSolved()
{
	if (xmlhttp.readyState == 4)
    {
        if(xmlhttp.status == 200)
        {
           var cellVal = xmlhttp.responseText;
           if (cellVal == 1) // value is invalid
           {
           	   timer_stop();
           	   
           	   alert("Congratulations, you have solved this sudoku!");
           	   m_Solved = true;
           	   htmlSaveSolved(m_iLevel);
           	   
           }
           else //value is valid
           {
           		alert("You are not finished yet!");
           }
        }
        else
        {
            alert("Error loading page\n"+ xmlhttp.status +":"+ xmlhttp.statusText);
        }
    }
}
//save solved statistic
function htmlSaveSolved(iLevel)
{
    var url = m_phpPath + 'savesolvedkid4.php';
    var sQryStr = "";

    if (window.ActiveXObject) {              // for IE
         xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
         }
    else if (window.XMLHttpRequest) {   // for other browsers{
         xmlhttp=new XMLHttpRequest();
    }

    xmlhttp.onreadystatechange=xmlhttpAswerSave;
    xmlhttp.open("POST",url,true);

    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    sQryStr = 'level=' + iLevel + '&duration=' + m_tSecs;
    xmlhttp.send(sQryStr);

}
function xmlhttpAswerSave()
{
	if (xmlhttp.readyState == 4)
    {
        if(xmlhttp.status == 200)
        {
           var saveStatus = xmlhttp.responseText;
        }
        else
        {
            //alert("Error loading page\n"+ xmlhttp.status +":"+ xmlhttp.statusText);
        }
    }
}
///////////////////////////
//   event functions     //
///////////////////////////
function add_event(element, evType, func) {
	if (element.addEventListener) {
		element.addEventListener(evType, func, false);
		return true;
	}
	else if (element.attachEvent) {
		var r = element.attachEvent('on' + evType, func);
		return r;
	}
	else {
		element['on' + evType] = func;
	}
}
function remove_event(element, evType, func) {
	if (element.removeEventListener) {
		element.removeEventListener(evType, func, false);
		return true;
	}
	else if (element.detachEvent) {
		var r = element.detachEvent('on' + evType, func);
		return r;
	}
	else {
		elm['on' + evType] = '';
	}
}
    
//Returns the target of the event.
function find_target(e) {
	var element;
	if (!e) var e = window.event;
	if (e.target) element = e.target;
	else if (e.srcElement) element = e.srcElement;
	if (element.nodeType == 3) element = element.parentNode;// Safari bug
	return element;
}

function watch_keys(e) {
	if (!e) var e = window.event;
	if (e.keyCode) code = e.keyCode;
	else if (e.which) code = e.which;
	var character = String.fromCharCode(code);

	//If the pressed key IS a number
	if(isNaN(character)) {
		alert(character + " is not a number.");
	}
}

///////////////////////////
//   timer functions     //
///////////////////////////
function timer_start()
{
	if (!m_tSecs) m_tSecs = 0;
	
	m_tSecs++;
	var s = m_tSecs % 60;
	var m = Math.floor(m_tSecs/60);
	if(s<10) s = "0" + s;
	if(m<10) m = "0" + m;  
	
	var e = document.getElementById("time");

	e.innerHTML = "Time: " + m + ":" + s;
	m_tObject = window.setTimeout("timer_start()",1000);

}
function timer_stop()
{
	if (m_tObject) window.clearTimeout(m_tObject);
}
function timer_switch()
{
	if (!m_sSudoku) return;
	
	if (m_tStarted){
		timer_stop();
		m_tStarted = false;
	} else {
		timer_start();
		m_tStarted = true;
	}
}
function timer_reset()
{
	timer_stop();
	
	var e = document.getElementById("time");
	e.innerHTML = "Time: 00:00";
}
function is_paused(){
	if (m_tStarted){
		return false;
	} else {
		return true;
	}
}
//debug status information
function status_set(message)
{
	var e = document.getElementById("status");
	e.innerHTML = message;
}
///////////////////////////
//   color functions     //
///////////////////////////
function readBackgroundColors(){
	
	var e, x, y, sElement;
	
	m_arBackgroundColors = new Array(16);
	m_arProblemCells = new Array();
	for (var i = 0; i < 16; i++)
    {
    	x = parseInt(i % 4) + 1;
        y = parseInt(i / 4) + 1;
        sElement = "txtC" + x + y;
        e = document.getElementById(sElement);
        m_arBackgroundColors[i] = e.style.background.toLowerCase();
        //alert(m_arBackgroundColors[i]);
    }
}
function setOriginalBackgroundColor(elementName){
	
	var x, y, sElement;
	for (var i = 0; i < 16; i++)
    {
    	x = parseInt(i % 4) + 1;
        y = parseInt(i / 4) + 1;
        sElement = "txtC" + x + y;
        if (sElement == elementName) {
        	 e = document.getElementById(sElement);
        	 e.style.background = m_arBackgroundColors[i];
        }
    }
 }
 function resetOriginalBackgroundColors(){
	
	var x, y, sElement;
	for (var i = 0; i < 16; i++)
    {
    	x = parseInt(i % 4) + 1;
        y = parseInt(i / 4) + 1;
        sElement = "txtC" + x + y;
  	 	e = document.getElementById(sElement);
        if (m_arBackgroundColors){
        	e.style.background = m_arBackgroundColors[i];
        }
    }
    m_arBackgroundColors = new Array(16);	
 }
 /////////////////////////////////
//   problem cell functions     //
//////////////////////////////////
 function addProblemCell(element) {
 
 	if (!isProblemCell(element.id)) {
 		m_arProblemCells.push(element.id);
 		element.style.background = m_wrongCellBackgroundColor;
 	}
 	//alert(elementName + " added as problem cell");
 }
 
 function removeProblemCell(elementName) {
 	var sElement;
	for (var i = 0; i < 16; i++)
    {
    	sElement = m_arProblemCells[i];
        if (sElement == elementName) {
        	 m_arProblemCells.splice(i, 1);
        	 //alert(elementName + " removed as problem cell");
        	 return;
        }
    }
    return(false);
 }
 
 function isProblemCell(elementName) {
 	var sElement;
	for (var i = 0; i < 16; i++)
    {
    	sElement = m_arProblemCells[i];
        if (sElement == elementName) {
        	 return(true);
        }
    }
    return(false);
}
//////////////////////////////////
//   cell readonly functions    //
//////////////////////////////////
function setReadOnly(element){
	// For IE
	if (window.ActiveXObject) {   
		element.setAttribute('readOnly', true);
	// Other browsers
	}else{
		element.setAttribute('readonly', true); 	
	}
}

function removeReadOnly(element){
	// For IE
	if (window.ActiveXObject) {   
		element.removeAttribute('readOnly'); 
	// Other browsers
	}else{
		element.removeAttribute('readonly'); 	
	}
}

/* level change */
function changeLevel()
{
	var e = document.getElementById("selLevel");
	var iLevel = e.value;
	
	if (m_gameStarted) {
		if (confirm("This will end your current game. Are you sure?") == false) {
			e.value = m_iLevel;
			return;
		}
	}
	
	m_iLevel = iLevel;
	switch(m_iLevel){
		case "3" : m_sLevel = "Difficult";break;
		case "2" : m_sLevel = "Standard";break;
		case "1" : m_sLevel = "Easy";break;
	}
	clear_grid();
	timer_reset();
	m_gameStarted = false;
	//set html properties to new level info	
	var e = document.getElementById("txtLevel");
	e.value = m_iLevel;
	var e = document.getElementById("levelHeader");
	e.innerHTML = "- " +  m_sLevel + " Level";
}
