
function resetColors() {
  for (var ligne=1; ligne <= 9; ligne++) {
    for (var col= 1; col <= 9; col++) {
      var cellName = String.fromCharCode(96+ligne)+col;
      var cell = document.getElementById(cellName);
      //if (cell.readOnly)
	  //  cell.style.backgroundColor = "#EEEEEE";
	  //else
	  cell.style.backgroundColor = "#FFFFFF";
    }
  }
}

function pause(obj) {
  var color;
  if (obj.value == "pause") {
  	obj.value = "reprendre";
  	color = "#FFFFFF";
  	pauseTimer();
  } else {
  	obj.value = "pause";
  	color = "#000000";
  	restartTimer();
  }
  for (var ligne=1; ligne <= 9; ligne++) {
    for (var col= 1; col <= 9; col++) {
      var cellName = String.fromCharCode(96+ligne)+col;
      var cell = document.getElementById(cellName);
	  cell.style.color = color;
    }
  }
}

function verifie() {
  resetColors();
  var wrong = new Array();
  // Lignes
  for (var ligne=1; ligne <= 9; ligne++) {
    var vals = new Array();
    for (var col= 1; col <= 9; col++) {
      var cellName = String.fromCharCode(96+ligne)+col;
      var cell = document.getElementById(cellName);
      if (vals[cell.value] == 1) {
        for (col= 1; col <= 9; col++) {
          wrong.push(String.fromCharCode(96+ligne)+col);
        }
      } else if (cell.value.length == 1)
        vals[cell.value]=1;
    }
  }

  // Cols
  for (var col= 1; col <= 9; col++) {
    var vals = new Array();
    for (var ligne=1; ligne <= 9; ligne++) {
      var cellName = String.fromCharCode(96+ligne)+col;
      var cell = document.getElementById(cellName);
      if (vals[cell.value] == 1) {
        for (ligne= 1; ligne <= 9; ligne++) {
          wrong.push(String.fromCharCode(96+ligne)+col);
        }
      } else if (cell.value.length == 1)
        vals[cell.value]=1;
    }
  }

  // Carres
  for (var cellL=0; cellL < 3; cellL++) {
    for (var cellC= 0; cellC < 3; cellC++) {
      var vals = new Array();
      for (var ligne=cellL*3+1; ligne <= cellL*3+3; ligne++) {
        for (var col=cellC*3+1; col <= cellC*3+3; col++) {
          var cellName = String.fromCharCode(96+ligne)+col;
          var cell = document.getElementById(cellName);
          if (vals[cell.value] == 1) {
            for (var ligne=cellL*3+1; ligne <= cellL*3+3; ligne++) {
              for (var col=cellC*3+1; col <= cellC*3+3; col++) {
                wrong.push(String.fromCharCode(96+ligne)+col);
              }
             }
          } else if (cell.value.length == 1)
            vals[cell.value]=1;
        }
      }
    }
  }

  var callReset = false;
  for (var index=0; index < wrong.length; index++) {
    callReset = true;
    cellName = wrong[index];
    var cell = document.getElementById(cellName);
    if (cell.style.backgroundColor == "rgb(255, 153, 153)")
      cell.style.backgroundColor = "#FF6666";
    else if (cell.style.backgroundColor == "rgb(255, 102, 102)")
      cell.style.backgroundColor = "#FF3333";
    else
      cell.style.backgroundColor = "#FF9999";
  }
  if (callReset)
    setTimeout("resetColors()", 5000);

  // Verification des cases
  if (soluce && soluce.length == 81) {
	  var index=0;
	  var bad=0;
	  var empty=0;
	  for (var ligne=1; ligne <= 9; ligne++) {
	    for (var col= 1; col <= 9; col++) {
	      var cellName = String.fromCharCode(96+ligne)+col;
	      var cell = document.getElementById(cellName);
	      if (cell.value.length == 1) {
	      	//alert(cell.value+"/"+soluce.substr(index, index+1));
	      	if (cell.value != soluce.substring(index, index+1))
	      		bad++;
	      } else
	      	empty++;
	      index++;
	    }
	  }
      var resultatSpan = document.getElementById("resultat");
      var resultat = new String();
      if (empty > 0)
      	resultat += " reste "+empty+" cases";
      if (bad > 0) {
      	if (resultat.length > 0)
      		resultat += ", ";
      	resultat += bad+" mauvaises réponses";
      }
      setValue(resultatSpan, resultat);
      if (bad == 0 && empty == 0) {
      	stopTimer();
      	doEndGame();
      }
	  setTimeout("clearResultat()", 5000);
  }

  return false;
}

function clearResultat() {
  var resultatSpan = document.getElementById("resultat");
  setValue(resultatSpan, "");
}


function doEndGame() {
  var resultatSpan = document.getElementById("felicitations");
  setValue(resultatSpan, "Félicitations, vous avez trouvé la bonne solution !");
}

var end;
function checkEnd() {
  // Verification des cases
  if (soluce && soluce.length == 81) {
  	var index=0;
	  for (var ligne=1; ligne <= 9; ligne++) {
	    for (var col= 1; col <= 9; col++) {
	      var cellName = String.fromCharCode(96+ligne)+col;
	      var cell = document.getElementById(cellName);
	      if (cell.value.length != 1 || cell.value != soluce.substring(index, index+1))
	  		return;
	      index++;
	    }
	  }
	  if (end)
	  	return;
	  end = true;
	  var newTime = new Date();
	  var diff=(newTime-time)/1000+totalSec;
	  stopTimer();
	  if (mpgame)
	  	sendSudokuEndMessage();
	  sendRequest('/local/transactions/endSudoku.php?id='+escape(getValue(numpartie))+"&time="+escape(diff), doEndGame);
  }
}

var stilldown = false;
function checkCell(cell) {
  stilldown=false;
  cell.value = cell.value.replace(/[^1-9]/g, "");
  if (cell.value.length > 1) {
    cell.style.fontSize = "10px";
  } else {
    cell.style.fontSize = "18px";
  }
  if (mpgame) {
  	sendSudokuMessage(cell);
  }
  checkEnd();
   return true;
}

function getKeyCode(e) {
    if (e && e.which)
        return e.which;
    else if (window.event && window.event.keyCode)
        return window.event.keyCode;
    //else
    //   return;
}

function handleKeyPress(e) {
    keyCode = getKeyCode();
    if (keyCode == 13)
		return false;
    	else if (keyCode >= 37 && keyCode <= 40) {
    		if (stilldown) return;
    		stilldown=true;
    		var ok = false;
    		var cell = e.target;
    		while (!ok) {
			var oldid = cell.id;
			var ligne = oldid.charCodeAt(0)-96;
			var col = oldid.substring(1,2);
			if (keyCode == 39)
				col = col%9+1;
			if (keyCode == 37) {
				col = (col-1);
				if (col == 0) col = 9;
			}
			if (keyCode == 40)
				ligne = ligne%9+1;
			if (keyCode == 38) {
				ligne = (ligne-1);
				if (ligne == 0) ligne = 9;
			}
			cell = document.getElementById(String.fromCharCode(96+ligne)+col);
			if (!cell.readOnly)
				ok=true;
		}
		cell.focus();
    	}

    //window.status += "keycode="+keyCode+"/target="+e.target.id+"/newid="+String.fromCharCode(96+ligne)+col+"/";
    //setTimeout("window.status=''", 5000);
}

function addListener(node, event, fct) {
  if (node.addEventListener) // W3C DOM Level 2
    node.addEventListener(event, fct, false);
  else if (node.attachEvent) // Fallback for IE/Windows
    node.attachEvent('on'+event, fct);
}

function newGame() {
	var numpartie = document.getElementById("numpartie");
	startGame(getValue(numpartie));
	return false;
}

function selectGame() {
	var numpartie = prompt("Sélectionnez un numéro de partie :");
	if (!isNaN(numpartie))
		chargeGame(numpartie);
	return false;
}

function startGame(previd) {
  sendRequest('/local/transactions/newSudoku.php?previd='+escape(previd), doStartGame);
}

function chargeGame(id) {
  sendRequest('/local/transactions/newSudoku.php?id='+escape(id)+'&nocookie=1', doStartGame);
}
var soluce;

function doStartGame() {

  if (http.readyState == 4) {
    end = false;
    var resultatSpan = document.getElementById("resultat");
    setValue(resultatSpan, "");
    var resultatSpan = document.getElementById("felicitations");
    setValue(resultatSpan, "");
    var cellContents = unescape(http.responseText);
    //cellContents = "1|||||||2|";
    var cells=cellContents.split("|");
    if (cells.length > 0) {
		var value = cells.shift();
		var numpartie = document.getElementById("numpartie");
		setValue(numpartie, value);
    }
    if (cells.length > 0) {
		var value = cells.shift();
		var objectif = document.getElementById("objectif");
		if (objectif)
			setValue(objectif, value);
    }
    if (cells.length > 0) {
		soluce = cells.shift();
    }
    var value;
    for (var ligne=1; ligne <= 9; ligne++) {
      for (var col= 1; col <= 9; col++) {
        var cellName = String.fromCharCode(96+ligne)+col;
        var cell = document.getElementById(cellName);
        cell.readOnly = false;
        cell.style.fontStyle = "normal";
        cell.style.backgroundColor = "#FFFFFF";
	    cell.style.fontSize = "18px";
	    var value
        if (cells.length > 0) {
          var value = cells.shift();
          if (value.length > 0) {
            cell.readOnly = true;
            cell.style.fontStyle = "italic";
            //cell.style.backgroundColor = "#EEEEEE";
            //cell.style.color = "#222222";
            //cell.value = value;
          }
        } else
        		value = "";
        cell.value = value;
        var cellName = "adv-"+String.fromCharCode(96+ligne)+col;
        var cell = document.getElementById(cellName);
        if (cell && value != "")
        	setValue(cell, value);
      }
    }
    if (cells.length > 0) {
		var value = cells.shift();
		var record = document.getElementById("record");
		if (record)
			setValue(record, value);
    }
    if (cells.length > 0) {
		var value = cells.shift();
		var niveau = document.getElementById("niveau");
		if (niveau)
			setValue(niveau, value);
    }
    startTimer();
  }
}

function setValue(obj, value) {
	if (obj.firstChild && obj.firstChild.nodeValue != null)
		obj.firstChild.nodeValue = value;
	else
		obj.innerText = value;
}

function getValue(obj) {
	if (obj.firstChild && obj.firstChild.nodeValue != null)
		return obj.firstChild.nodeValue;
	else
		return obj.innerText;
}

var time;
var totalSec;
var timeDisplay;
var timer;

function displayTimer() {
	if (timeDisplay && time) {
		var newTime = new Date();
		var diff=(newTime-time)/1000+totalSec;
		var sec=Math.floor(diff%60);
		var min=Math.floor(diff/60);
		var strTime = sec;
		if (sec < 10)
			strTime = min+":0"+sec;
		else
			strTime = min+":"+sec;
		setValue(timeDisplay, strTime);
	}
}
function startTimer() {
	stopTimer();
	timeDisplay = document.getElementById("chrono");
	time = new Date();
	totalSec = 0;
	timer = setInterval("displayTimer()", 1000);
}
function stopTimer() {
	if (timer)
		clearInterval(timer);
}
function pauseTimer() {
	var newTime = new Date();
	var diff=(newTime-time)/1000;
	totalSec += diff;
	stopTimer();
}
function restartTimer() {
	stopTimer();
	time = new Date();
	timer = setInterval("displayTimer()", 1000);
}

// Multijoueur

function handleMsg(message) {
    if (message.length > 0) {
	    var debugSpan = document.getElementById("debug");
	    if (debugSpan)
		    setValue(debugSpan, message+" R="+lastIdRcv+"/S="+lastIdSent);
	}
	var parts = message.split("|");
	if (parts[0] == "I" || parts[1] == "I") {
		//I|31207|0|azertyudfc|Jeux de cartes.net
		var offset;
		if (parts[1] == "I")
			offset=1
		else
			offset = 0;
		setTimeout("chargeGame("+parts[1+offset]+")", 500);
		var adv = document.getElementById("adv-name");
		if (parts[3+offset] == nomJoueur) {
			quiSuisJe=0;
			setValue(adv, parts[4+offset]);
		} else {
			quiSuisJe=1;
			setValue(adv, parts[3+offset]);
		}
	} else if (message.substring(1, 2) == "F") {
		var resultat = document.getElementById("resultat");
		if (message.substring(2,3) == quiSuisJe) {
			setValue(resultat, "Vous avez été le plus rapide !");
		} else {
			setValue(resultat, "Votre adversaire a été plus rapide que vous !");
		}
	} else {
		parts.shift();
		  for (var ligne=1; ligne <= 9; ligne++) {
		    for (var col= 1; col <= 9; col++) {
		      var cellName = "adv-"+String.fromCharCode(96+ligne)+col;
		      var cell = document.getElementById(cellName);
		      var value = parts.shift();
		      if (value.length == 1) {
		      	if (getValue(cell) != value)
					cell.style.backgroundColor = "#CCCCCC";
		      	setValue(cell, value);
			  } else if (value.length == 0)
			    if (getValue(cell) != " ")
			      setValue(cell, " ");
				cell.style.backgroundColor = "#FFFFFF";
		    }
		  }
	}
}

var lastSent;

function sendSudokuMessage(cell) {
	var message = "S";
  for (var ligne=1; ligne <= 9; ligne++) {
    for (var col= 1; col <= 9; col++) {
      var cellName = String.fromCharCode(96+ligne)+col;
      var cell = document.getElementById(cellName);
      message += "|"+cell.value;
    }
  }
  if (message != lastSent) {
	  lastSent = message;
	  sendMessage(message, true);
  }
}

function sendSudokuEndMessage() {
	sendMessage("V100");
}

function setCookie(nom, valeur) {
	var argv=setCookie.arguments;
	var argc=setCookie.arguments.length;
	var expires=(argc > 2) ? argv[2] : null;
	var path=(argc > 3) ? argv[3] : null;
	var domain=(argc > 4) ? argv[4] : null;
	var secure=(argc > 5) ? argv[5] : false;
	document.cookie=nom+"="+escape(valeur)+
		((expires==null) ? "" : ("; expires="+expires.toGMTString()))+
		((path==null) ? "" : ("; path="+path))+
		((domain==null) ? "" : ("; domain="+domain))+
		((secure==true) ? "; secure" : "");
}
