var aNivelActual = new Array();
var nNivelActual = 1;
var maxH = 0; //numero maximo de columnas
var maxV = 0; //numero maximo de filas
var numObjetivos = 0;
var numTesorosColocados = 0;
var w = 13;
var h = 13;
var skin = "eGoogle";
var dirSkin = "img/";
var skinPorDefecto = 4;
var esParedSimple = true;
var strDeshacer = "";
var conjuntoDeNiveles = "";


function inicio(){
	//inicializarNivel();
	pintarInfoNivel();
		
	stTxt = "<a href=\"javascript:setNivel('-')\"><img src=\"img/nivelAnt.gif\"></a><strong>Level " + nNivelActual + "</strong><a href=\"javascript:setNivel('+')\"><img src=\"img/nivelPost.gif\"></a>";
	document.getElementById("c1").innerHTML = stTxt;
		
	stTxt = "<a href=\"javascript:deshacer()\"><img src=\"img/undo.gif\"></a>";
	document.getElementById("c2").innerHTML = stTxt;
		
	stTxt = "<a href=\"javascript:reiniciarNivel()\" title=\"Try Again\"><img src=\"img/restart.gif\"></a>";
	document.getElementById("c3").innerHTML = stTxt;
		
	stTxt = "<a href=\"javascript: irA_inicio()\" title=\"Go to Level 1\"><img src=\"img/nivel0.gif\"></a>";
	document.getElementById("c4").innerHTML = stTxt;
}

function irA_inicio(){
	deleteCookie("skbn160_nivel");
	deleteCookie("skbn160_estado");
	window.location.href="index.html";
}

function pintarInfoNivel(){
	var nivel = getCookie("skbn160_nivel");
	if (nivel=="") {nivel=1};
	if (nivel > numNiveles) {
		stTxt  = "";
		stTxt += "<div style=\"background:url('img/bg.jpg') 0 0 no-repeat; width: 100%; height: 143px; text-align: center;\">";
		stTxt += "	<div style=\"padding: 15px; padding-top: 25px; \"><b>Congratulations!!!</b><br>You have finished this set of levels.<br><br>If you want to continue playing visit <a href=\"http://sokoban.e-contento.com/en.index.php\" target=\"_blanck\">Sokoban en JavaScript</a></div>";
		stTxt += "</div>";
		document.getElementById("cJuego").innerHTML = stTxt;
	}else{
		nNivelActual = nivel;
		
		autor = eval("nivel_" + nivel + "_autor");
		name  = eval("nivel_" + nivel + "_name");
		
		stTxt  = "";
		stTxt += "<div style=\"background:url('img/bg.jpg') 0 0 no-repeat; width: 100%; height: 143px; text-align: center;\" onclick=\"inicializarNivel()\">";
		stTxt += "	<div style=\"padding-top: 25px; padding-bottom: 15px; text-decoration: underline;\"><b>Level " + nivel + "</b></div>";
		stTxt += "	<div style=\"text-align: left; padding: 5px;\">";
		stTxt += "		<b>Name:</b> " +  name + "<br>";
		stTxt += "		<b>Autor:</b> " + autor + "<br>";
		stTxt += "	</div>";
		stTxt += "	<div style=\"text-align: center; padding-top: 25px;\">(Click to play)</div>";
		stTxt += "</div>";
		document.getElementById("cJuego").innerHTML = stTxt;
	}
}


	
function recargar(){
	window.location.href = "sokoban.html";
	return;
}

function deshacer(){
	if (strDeshacer.charAt(strDeshacer.length-1)=="|"){
	 	strDeshacer = strDeshacer.substring(0,strDeshacer.length-1);
	}
	strMovimiento = strDeshacer.substring(strDeshacer.lastIndexOf("|")+1,strDeshacer.length-1);
	eval(strMovimiento);
	strDeshacer = strDeshacer.substring(0,strDeshacer.lastIndexOf("|"));
}

function setConjunto(strConjunto){
	if (getCookie("skbn160_estado")!="" || getCookie("skbn160_nivel")!=""){
		
	}else{
		setCookie("skbn160_conjuntoDeNiveles",strConjunto,getExpDate(180, 0, 0));
		reiniciarJuego(); 
	}
}


function setNivel(num){
	if(num!="+" && num!="-"){
		setCookie("skbn160_nivel",num,getExpDate(180, 0, 0));
		reiniciarNivel(); 
	}else{
		i = 1*getCookie("skbn160_nivel");
		if (num=="+"){
			setNivel(i+1)
		}else{
			if (i>0){
				setNivel(i-1);
			}
		}
	}
}


// manejo de imagenes
var iBlanco    = new Image();   iBlanco.src    = dirSkin + "sp.gif";
var iPared     = new Image();   iPared.src     = dirSkin + "pared.gif";
var iObjetivo  = new Image();   iObjetivo.src  = dirSkin + "objetivo.gif";
var iJugador   = new Image();   iJugador.src   = dirSkin + "jugador.gif"
var iOJugador  = new Image();   iOJugador.src  = dirSkin + "ojugador.gif"
var iTesoro    = new Image();   iTesoro.src    = dirSkin + "tesoro.gif"
var iOTesoro   = new Image();   iOTesoro.src   = dirSkin + "otesoro.gif"

function cambiar(idImg,idImgNueva) {
  document.images[idImg].src = eval(idImgNueva).src;
  //el 1er parametro es el nombre de la imagen
  //el 2o parametro es la que queremos cambiar
}

function inicializarNivel(){
	var nivel = getCookie("skbn160_nivel");
	var estado = getCookie("skbn160_estado");

	if (nivel>numNiveles){
		deleteCookie("skbn160_nivel");
		deleteCookie("skbn160_estado");
		//setConjunto("clasicos");
	}else{
		
		if (nivel=="") {nivel=1};
		if (estado==""){
			nNivelActual = nivel;
			nivel = eval("nivel_" + nivel);
			aNivelActual = nivel.split("|");	
		}else{
			nNivelActual = nivel;
			aNivelActual = estado.split("|");
		}
		

		var txt = ""	
		txt = "<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" align=\"center\">"
		for (i=0;i<aNivelActual.length;i++){
			txt += "<tr height=\"" + h + "\">";
			for(j=0;j<aNivelActual[i].length;j++){
				switch (aNivelActual[i].charAt(j)){
					case "#": //pared
						imagen = dirSkin + "pared.gif";
						break;
					case "@": //jugador
						imagen = dirSkin + "jugador.gif";
						posV   = i;
						posH   = j;
						break;
					case ".": //objetivo
						imagen = dirSkin + "objetivo.gif";
						numObjetivos = numObjetivos + 1;
						break;
					case "$": //tesoro
						imagen = dirSkin + "tesoro.gif";
						break;
					case "*": //tesoro sobre objetivo
						imagen = dirSkin + "otesoro.gif";
						numTesorosColocados = numTesorosColocados + 1;
						numObjetivos = numObjetivos + 1;
						break;
					case "+": //jugador sobre objetivo
						imagen = dirSkin + "ojugador.gif";
						posV   = i;
						posH   = j;
						numObjetivos = numObjetivos + 1;
						break;
					case " ": //espacio
						imagen = dirSkin + "sp.gif";
						break;
				}
	
				txt +="<td id=\"td_x" + i + "y" + j + "\" width=\"" + w + "\"><img src=\"" + imagen + "\" width=\"" + w + "\" height=\"" + h + "\" name=\"img_x" + i + "y" + j + "\" ></td>";
			}
			txt += "</tr>";
			if (maxH< ( aNivelActual[i].length - 1)){
				maxH = aNivelActual[i].length - 1;
			}
		}
		txt += "</table>";
		if (maxV < (aNivelActual.length - 1)){
			maxV = aNivelActual.length - 1;
		}
		document.getElementById("cJuego").innerHTML = txt;
	}
}


function reiniciarNivel(){
	deleteCookie("skbn160_estado");
	recargar();
}


function reiniciarJuego(){
	deleteCookie("skbn160_nivel");
	deleteCookie("skbn160_estado");
	recargar();
}

function pintarEstado(){
	txt = "";
	for (i=0;i<aNivelActual.length;i++){
		txt = txt + aNivelActual[i] + "|";	
	}
	fechaExp = getExpDate(180, 0, 0);
	setCookie("skbn160_estado",txt,fechaExp);
	if (numTesorosColocados==numObjetivos){
		deleteCookie("skbn160_estado");
		setCookie("skbn160_nivel",parseInt(nNivelActual)+1,fechaExp);
		recargar();	
	}
}

function handleCursores(evt) {
    evt = (evt) ? evt : ((window.event) ? event : null);
    if (evt) {
        switch (evt.keyCode) {
            case 37: //izquierda
    			if(posH>0){
    				if (aNivelActual[posV].charAt(posH-1)==" " || aNivelActual[posV].charAt(posH-1)=="."){
   						inJugador(posV,posH-1);	
   						outBloque(posV,posH);
						
						strDeshacer += "inJugador(" + posV + "," + (posH) + ");";
						strDeshacer += "outBloque(" + posV + "," + (posH-1) + ");";
						strDeshacer += "posH=" + posH + ";";
						strDeshacer += "|";
						
						posH = posH - 1;
					}else if (aNivelActual[posV].charAt(posH-1)=="$" || aNivelActual[posV].charAt(posH-1)=="*"){
						if(posH-2>0){
							c = aNivelActual[posV].charAt(posH-2);
							if (c == " " || c == "."){
								inTesoro(posV,posH-2);
								outBloque(posV,posH-1);
								inJugador(posV,posH-1);
								outBloque(posV,posH);
								
								strDeshacer += "inJugador(" + posV + "," + (posH) + ");";
								strDeshacer += "outBloque(" + posV + "," + (posH-1) + ");";
								strDeshacer += "inTesoro(" + posV + "," + (posH-1) + ");";
								strDeshacer += "outBloque(" + posV + "," + (posH-2) + ");";
								strDeshacer += "posH=" + posH + ";";
								strDeshacer += "|";
								
								posH = posH - 1;
							}
						}
					}
    			}
                break;    
            case 38: //arriba
            	if(posV>0){
            		if (aNivelActual[posV-1].charAt(posH)==" " || aNivelActual[posV-1].charAt(posH)=="."){
						inJugador(posV-1,posH);
						outBloque(posV,posH);
						
						strDeshacer += "inJugador(" + posV + "," + posH + ");";
						strDeshacer += "outBloque(" + (posV-1) + "," + posH + ");";
						strDeshacer += "posV=" + posV + ";";
						strDeshacer += "|";
						
						posV = posV - 1;
					}else if (aNivelActual[posV-1].charAt(posH)=="$" || aNivelActual[posV-1].charAt(posH)=="*"){
						if(posV-2>0){
							c = aNivelActual[posV-2].charAt(posH);
							if (c == " " || c == "."){
								inTesoro(posV-2,posH);
								outBloque(posV-1,posH);
								inJugador(posV-1,posH);
								outBloque(posV,posH);
								
								strDeshacer += "inJugador(" + posV + "," + posH + ");";
								strDeshacer += "outBloque(" + (posV-1) + "," + posH + ");";
								strDeshacer += "inTesoro(" + (posV-1) + "," + posH + ");";
								strDeshacer += "outBloque(" + (posV-2) + "," + posH + ");";
								strDeshacer += "posV=" + posV + ";";
								strDeshacer += "|";
								
								posV = posV - 1;
							}	
						}
    				}
    			}
                break;    
            case 39: //derecha
            	if(posH<maxH){
            		if (aNivelActual[posV].charAt(posH+1)==" " || aNivelActual[posV].charAt(posH+1)=="."){
						inJugador(posV,posH+1);
						outBloque(posV,posH);
						
						strDeshacer += "inJugador(" + posV + "," + (posH) + ");";
						strDeshacer += "outBloque(" + posV + "," + (posH+1) + ");";
						strDeshacer += "posH=" + posH + ";";
						strDeshacer += "|";
						
						posH = posH + 1;
					}else if (aNivelActual[posV].charAt(posH+1)=="$" || aNivelActual[posV].charAt(posH+1)=="*"){
						if(posH+2<maxH){
							c = aNivelActual[posV].charAt(posH+2);
							if (c == " " || c == "."){
								inTesoro(posV,posH+2);
								outBloque(posV,posH+1);
								inJugador(posV,posH+1);
								outBloque(posV,posH);
								
								strDeshacer += "inJugador(" + posV + "," + (posH) + ");";
								strDeshacer += "outBloque(" + posV + "," + (posH+1) + ");";
								strDeshacer += "inTesoro(" + posV + "," + (posH+1) + ");";
								strDeshacer += "outBloque(" + posV + "," + (posH+2) + ");";
								strDeshacer += "posH=" + posH + ";";
								strDeshacer += "|";
								
								posH = posH + 1;
							}	
						}
    				}
    			}
                break;    
            case 40: //abajo
            	if(posV<maxV){
            		if (aNivelActual[posV+1].charAt(posH)==" " || aNivelActual[posV+1].charAt(posH)=="."){
						inJugador(posV+1,posH);
						outBloque(posV,posH);
						
						strDeshacer += "inJugador(" + posV + "," + posH + ");";
						strDeshacer += "outBloque(" + (posV+1) + "," + posH + ");";
						strDeshacer += "posV=" + posV + ";";
						strDeshacer += "|";
								
						posV = posV + 1;
					}else if(aNivelActual[posV+1].charAt(posH)=="$" || aNivelActual[posV+1].charAt(posH)=="*"){
						if(posV+2<maxV){
							c = aNivelActual[posV+2].charAt(posH);
							if (c == " " || c == "."){
								inTesoro(posV+2,posH);
								outBloque(posV+1,posH);
								inJugador(posV+1,posH);
								outBloque(posV,posH);
								
								strDeshacer += "inJugador(" + posV + "," + posH + ");";
								strDeshacer += "outBloque(" + (posV+1) + "," + posH + ");";
								strDeshacer += "inTesoro(" + (posV+1) + "," + posH + ");";
								strDeshacer += "outBloque(" + (posV+2) + "," + posH + ");";
								strDeshacer += "posV=" + posV + ";";
								strDeshacer += "|";
								
								posV = posV + 1;
							}	
						}
    				}
    			}
                break;    
         }
    }
    stopBubbleEvent(evt); 
    pintarEstado();
}

function stopBubbleEvent(e){
	//e.cancelBubble is supported by IE - this will kill the bubbling process.
	if (document.all){
		e.keyCode = 0;
		e.cancelBubble = true;
		e.returnValue = false;
		e.retainFocus = true;
	}

	//e.stopPropagation works in Firefox.
	if (e.stopPropagation) {
		e.stopPropagation();
		e.preventDefault();
	}
	return false;
}


function outBloque(pVO,pHO){
	iO = iBlanco;
	cO = ' ';

	var idOrigen  = "img_x" + pVO + "y" + pHO;
	
	vTemp = document.images[idOrigen].src.split("/");
	iTemp = vTemp[vTemp.length-1];
	if (iTemp.charAt(0)== "o"){
		iO = iObjetivo;
		cO = '.';	
	}
	if (iTemp.split(".")[0]=="otesoro"){
		numTesorosColocados = numTesorosColocados - 1;
	}
	
	escribirEstado(pVO,pHO,cO);
	cambiar(idOrigen,iO);
}



function inTesoro(pVO,pHO){
	iO = iTesoro;
	cO = '$';

	var idOrigen  = "img_x" + pVO + "y" + pHO;
	
	vTemp = document.images[idOrigen].src.split("/");
	if (vTemp[vTemp.length-1].charAt(0)== "o"){
		iO = iOTesoro;
		cO = '*';
		numTesorosColocados = numTesorosColocados + 1;
	}
	
	escribirEstado(pVO,pHO,cO);
	cambiar(idOrigen,iO);
}



function inJugador(pVO,pHO){
	iO = iJugador;
	cO = '@';

	var idOrigen  = "img_x" + pVO + "y" + pHO;
	
	vTemp = document.images[idOrigen].src.split("/");
	if (vTemp[vTemp.length-1].charAt(0)== "o"){
		iO = iOJugador;
		cO = '+';	
	}
	
	escribirEstado(pVO,pHO,cO);
	cambiar(idOrigen,iO);
}



function escribirEstado(pV,pH,letra){
	var txtEstado = "";
	for (i=0;i<aNivelActual[pV].length;i++){
		if (i==pH){
			txtEstado = txtEstado + letra;
		}else{
			txtEstado = txtEstado + aNivelActual[pV].charAt(i);
		}
	}
	aNivelActual[pV] = txtEstado;
}