
//netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserWrite"); 

var color = new Array([]);
var fichas = new Array([]);
var fichasOld = new Array([]);
var dir = "img/";
var gridx = 10;
var gridy = 16;
var anchoScores =30;
var altoScores =20;
var tituloHeight =18;
var interWidth =10;
var menuHeight =35;
var wideWidth = 0;
var highHeight = 0;
var undo=false;
var reiniciar=false;
var scoreTipe="highscore";
var Auxsquaresleft=0;
var score =0;
var Totalsquares = gridy * gridx;
var squaresleft = Totalsquares;	
var u=1;
var interior = "";
var colores = 4;
var s = "";
var email = "";
var galleta = "clickIgnacioJaureguizar"

color[1]="#FF8400";
color[2]="#008400";
color[3]="#FF0000";
color[4]="#0106E1";
color[5]="#C6C3C6";
color[6]="#DED600";
color[7]="#0105BB";
color[8]="#9A0095";
color[9]="#008284";

for(y = 0; y < gridy; ++y)
{
	fichas[y] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
	fichasOld[y] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];	
}


function cerrarPreferencias(){
	divPreferencias.hide()
}

function restorePreferencias(){
	f=document.fpreferencias;
	f.email.value=""
	f.filas.value="16"
	f.columnas.value="10"
	f.colores.value="5"
	f.puntuacion.selectedIndex=0
	salvarPreferencias()
}



function salvarPreferencias(){
	reiniciar=false;
	
	f=document.fpreferencias;
	if(gridy!=f.filas.value||gridx!=f.columnas.value||colores!=f.colores.value||scoreTipe!=f.puntuacion.options[f.puntuacion.selectedIndex].value)
		reiniciar=true;
		
	email=f.email.value
	gridy=f.filas.value
	if(f.columnas.value>16){
		alert("no puede ser mayor de 16")
		f.columnas.value=gridx
	}
	else
		gridx=f.columnas.value
		
	colores=f.colores.value
	if(f.puntuacion.selectedIndex==1)
		scoreTipe="lowscore"
	else 
		scoreTipe="highscore"
		
	divPreferencias.hide()
	enviarDatos();
	if (reiniciar)
		start();
}

function abrirPreferencias(){
 	f=document.fpreferencias;
	f.email.value=email
	f.filas.value=gridy
	f.columnas.value=gridx
	f.colores.value=colores
	if(scoreTipe=="lowscore")
		f.puntuacion.selectedIndex=1
	else 
		f.puntuacion.selectedIndex=0
	
	divPreferencias.show()
}

//almacenar cookie con los datos del tecnico
function mandarGalleta(nombre, valor, caducidad) 
{
  document.cookie = nombre + "=" + escape(valor)+ ((caducidad == null) ? "" : ("; expires=" + caducidad.toGMTString()))
}
//leer los datos de la cookie
function consultarGalleta(nombre) {
  var buscamos = nombre + "=";
  if (document.cookie.length > 0) {
    i = document.cookie.indexOf(buscamos);
    if (i != -1) {
      i += buscamos.length;
      j = document.cookie.indexOf(";", i);
      if (j == -1)
        j = document.cookie.length;
      return unescape(document.cookie.substring(i,j));
    }
  }
}
function enviarDatos()
{
	var caducidad=new Date (2004, 12, 31);//cambiar fecha!!!
	mandarGalleta(galleta+"email",email, caducidad);
	mandarGalleta(galleta+"gridy",gridy, caducidad);
	mandarGalleta(galleta+"gridx",gridx, caducidad);
	mandarGalleta(galleta+"colores",colores, caducidad);
	mandarGalleta(galleta+"scoreTipe",scoreTipe, caducidad);
}
//mostar los datos de la cookie en el formulario
function cargarDatos()
{	
	f=document.fpreferencias;
	if (consultarGalleta(galleta+"email")){
		email = consultarGalleta(galleta+"email");
		f.email.value =email
		}
	if (consultarGalleta(galleta+"gridy")){
		gridy = consultarGalleta(galleta+"gridy");
		f.filas.value = gridy
		}
	if (consultarGalleta(galleta+"gridx")){
		 gridx=consultarGalleta(galleta+"gridx");
		 f.columnas.value =gridx
		}
	if (consultarGalleta(galleta+"colores")){
		colores=consultarGalleta(galleta+"colores");
		f.colores.value = colores
		}
	if (consultarGalleta(galleta+"scoreTipe")){
		scoreTipe = consultarGalleta(galleta+"scoreTipe");
		if(scoreTipe=="lowscore")
			f.puntuacion.selectedIndex=1
		else 
			f.puntuacion.selectedIndex=0
	}
}

function over(id){
	if(id!='undo'||undo)
		document.images[id].src=dir +id+"_over.gif"
	}
function out(id){
	if(id=='undo'&&!undo)
		document.images[id].src=dir +id+"_init.gif"
	else
		document.images[id].src=dir +id+".gif"
	}
function down(id){
	if(id!='undo'||undo)
		document.images[id].src=dir +id+"_on.gif"
	}
	
function ayuda(){
	alert("Simplemente, pincha en los cuadrados que esten rodeados de otros cuadrados de su mismo color, \n hasta que elimines todos \n Si deseas guardar tu resultado debes de introducir el email en Preferencias");
}	

function acerca(){
	alert("Ignacio Jaureguizar (i_jaureELIMINA@hotmail.com) es el gran autor del juego en su Version WEB, \n basandose en el programa de Matthias Schussler Clickomania");
}	

function minimizar(){
	window.resizeTo(wideWidth+divTitulo.getX(),0);	
}		

/*// Function to calculate the number of mines adjacent to a grid location
function surrounding(y,x) {
	var count = 0;
	if (y > 0 && x > 0 && mines[y-1][x-1]) count++;
	if (y > 0 && mines[y-1][x]) count++;
	if (y > 0 && x < gridx-1 && mines[y-1][x+1]) count++;
	if (x > 0 && mines[y][x-1]) count++;
	if (x < gridx-1 && mines[y][x+1]) count++;
	if (y < gridy-1 && x > 0 && mines[y+1][x-1]) count++;
	if (y < gridy-1 && mines[y+1][x]) count++;
	if (y < gridy-1 && x < gridx-1 && mines[y+1][x+1]) count++;
	return count;
}*/

function restart() {
	start()
}

function start() {

	cargarDatos();
	for(y = 0; y < gridy; ++y)
	{
		fichas[y] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
		fichasOld[y] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];	
	}
	//iniciar variables
	undo=false;
	Auxsquaresleft=0;
	score =0;

	Totalsquares = gridy * gridx;
	squaresleft = Totalsquares;	
	wideWidth = 2+(gridx * 21);
	if(wideWidth<180)
		wideWidth=180;
	highHeight = 2+(gridy * 21);
	u=1;
	interior = "";

	divPreferencias= new JSFX.Layer(JSFX.findLayer("Preferencias"));

	divTitulo = new JSFX.Layer(JSFX.findLayer("Titulo"));
	divTitulo.resizeTo(wideWidth,tituloHeight)
	
	posicionX=divTitulo.getX();
	posicionY=divTitulo.getY();

	divMenu= new JSFX.Layer(JSFX.findLayer("Menu"));
	divMenu.resizeTo(wideWidth,menuHeight)
	divMenu.moveTo(posicionX,posicionY+tituloHeight)

	divMarcoTablero= new JSFX.Layer(JSFX.findLayer("MarcoTablero"));
	divMarcoTablero.setContent(codigoDelTablero(true))
	divMarcoTablero.resizeTo(wideWidth,highHeight)
	divMarcoTablero.moveTo(posicionX,posicionY+tituloHeight+menuHeight)
	
	divFondo = new JSFX.Layer(JSFX.findLayer("Fondo"));
	divFondo.resizeTo(wideWidth+6,tituloHeight+menuHeight+highHeight+altoScores+6)
	divFondo.moveTo(posicionX-3,posicionY-3)
	interior="<table width='"+(wideWidth+6)+"' height='"+(tituloHeight+menuHeight+highHeight+altoScores+6)+"'><tr><td nowrap width='100%' height='100%' >&nbsp;</td></tr></table>"
	//div de informacion
	posicionY2=posicionY+tituloHeight+menuHeight+highHeight
	
	divIniciales = new JSFX.Layer(JSFX.findLayer("iniciales"));
	divIniciales.setContent("<table><tr><td nowrap><font size=2>"+Totalsquares+"</font></td></tr></table>")
	divIniciales.resizeTo(anchoScores,altoScores)
	divIniciales.moveTo(posicionX,posicionY2)

	divRestan = new JSFX.Layer(JSFX.findLayer("restan"));
	divRestan.setContent("<table><tr><td nowrap><font size=2>"+Totalsquares+"</font></td></tr></table>")
	divRestan.resizeTo(anchoScores,altoScores)
	divRestan.moveTo(posicionX+divIniciales.getWidth(),posicionY2)


	divPuntuacion = new JSFX.Layer(JSFX.findLayer("puntos"));
	divPuntuacion.setContent("<table><tr><td nowrap><font size=2>"+0+"</font></td></tr></table>")
	divPuntuacion.resizeTo(anchoScores,altoScores)
	divPuntuacion.moveTo(posicionX+divIniciales.getWidth()+divRestan.getWidth(),posicionY2)
	
	divMensajes = new JSFX.Layer(JSFX.findLayer("mensajes"));
	divMensajes.setContent("<table><tr><td nowrap><font size=2>"+"&iexcl;Adelante!"+"</font></td></tr></table>")
	divMensajes.resizeTo(wideWidth-divIniciales.getWidth()-divRestan.getWidth()-divPuntuacion.getWidth(),altoScores)
	divMensajes.moveTo(posicionX+divIniciales.getWidth()+divRestan.getWidth()+divPuntuacion.getWidth(),posicionY2)	
	
	divCargando = new JSFX.Layer(JSFX.findLayer("cargando"));
	divCargando.hide();

}

function codigoDelTablero(inicio){
	HTML="";
	var y,x;
	var s = "";
	
	if(gridx<=16){
		s = s + '<table border="0" cellpadding="0" cellspacing="0"  >'
		for(y = 0; y < gridy; ++y)
		{
			s = s + '<tr>'
			for(x = 0; x < gridx; ++x)
			{
				/*s = s + '<a href="javascript:gridclick(' + y + ',' + x +');">' +'<img src="' ;
				fichas[y][x]=dir + (Math.floor(Math.random()*colores)+1) + '.gif';
				s = s + fichas[y][x];
				s = s + '" name="grd'+y+'_'+x+'" border=0></a>'*/
				
				s = s + '<td onclick="gridclick(' + y + ',' + x +');" width="21" height="21"  bgColor="';
				//fichas[y][x]=dir + (Math.floor(Math.random()*colores)+1) + '.gif';
				if(inicio)
					fichas[y][x]=color[Math.floor(Math.random()*colores)+1];
				
				s = s + fichas[y][x];
				s = s + '" >&nbsp;</td>'
			}
			s = s + "</tr>";
		}
		s = s + '</table>'
	}else{
		alert("X debe ser menor de 16!");
		return "";
	}

	HTML=HTML+"<table width='100%' height='100%' border='0' cellpadding='0' cellspacing='0' id='tbMarcoTablero'>";
	HTML=HTML+"	<tr> ";
	HTML=HTML+"		<td bgcolor='#000000'><img src='img/a.gif' width='1' height='1'></td>";
	HTML=HTML+"		<td bgcolor='#000000'><img src='img/a.gif' width='1' height='1'></td>";
	HTML=HTML+"		<td bgcolor='#000000'><img src='img/a.gif' width='1' height='1'></td>";
	HTML=HTML+"	</tr>";
	HTML=HTML+"	<tr> ";
	HTML=HTML+"		<td bgcolor='#000000'><img src='img/a.gif' width='1' height='1'></td>";
	HTML=HTML+"		<td width='100%' nowrap>"+s+"</td>";
	HTML=HTML+"		<td bgcolor='#000000'><img src='img/a.gif' width='1' height='1'></td>";
	HTML=HTML+"	</tr>";
	HTML=HTML+"	<tr> ";
	HTML=HTML+"		<td bgcolor='#000000'><img src='img/a.gif' width='1' height='1'></td>";
	HTML=HTML+"		<td bgcolor='#000000'><img src='img/a.gif' width='1' height='1'></td>";
	HTML=HTML+"		<td bgcolor='#000000'><img src='img/a.gif' width='1' height='1'></td>";
	HTML=HTML+"	</tr>";
	HTML=HTML+"</table>";
	return HTML;
 }
        

function restaurar(a,b){
	var x,y;
	for(y = 0; y < gridy; ++y)
	{
		for(x = 0; x < gridx; ++x)
			a[y][x]=b[u][y][x];
	}
}

function almacenar(a,b){
	var x,y;
	for(y = 0; y < gridy; ++y)
	{
		for(x = 0; x < gridx; ++x)
			b[u][y][x]=a[y][x];
	}
}
function copiar(a,b){
	var x,y;
	for(y = 0; y < gridy; ++y)
	{
		for(x = 0; x < gridx; ++x)
			b[y][x]=a[y][x];
	}
}

function deshacer(){
	if(undo)
	{
		u--
		copiar(fichasOld,fichas)
		squaresleft=squaresleftOLD;
		score=scoreOLD;
		foto();
		divMensajes.setContent("deshecho")
		divRestan.setContent("<table><tr><td nowrap><font size=2>"+squaresleft+"</font></td></tr></table>")
		divPuntuacion.setContent("<table><tr><td nowrap><font size=2>"+score+"</font></td></tr></table>")
	}
	undo=false;
	out('undo')
	if(u==1){
		document.images["undo"].src=dir +"undo_init.gif"
	}
}

////funcionamiento////////////////
function rollback(y,x) {
	
	if (y >= 0 && y < gridy && x >=0 && x < gridx){
		imagen=fichas[y][x];
//		 if((imagen!=dir + "nomine.gif") && (imagenOrig!=dir + "sq0.gif"))	
		 if((imagen!="#D6D3CE") && (imagenOrig!="#FFFFFF"))	 
		 {			
			if (imagen==imagenOrig) {
				//alert(y+""+x)
				squaresleft--;
				fichas[y][x] = "#D6D3CE"//dir + "nomine.gif";
				rollback(y-1,x);
				rollback(y,x-1);
				rollback(y,x+1);
				rollback(y+1,x);
	     	 	}
	     	 }
  	 }
  	 //else
  	 	//alert("como has conseguido las coordenadas"+y +" "+x+"??")
}

function finalizado() {
	var x, y;
	for(y = 0; y < gridy-1; ++y) {
		for(x = 0; x < gridx-1; ++x) {
			if((fichas[y][x]==fichas[y+1][x]||fichas[y][x]==fichas[y][x+1])&&fichas[y][x]!="#FFFFFF")//dir + "sq0.gif")
				{
					return false	
				}
		}
	}

	for(x = 0; x < gridx-1; ++x) {
		if(fichas[gridy-1][x]==fichas[gridy-1][x+1]&&fichas[gridy-1][x]!="#FFFFFF")//dir + "sq0.gif")
				{
					return false	
				}
	}
	
	for(y = 0; y < gridy-1; ++y) {
		if(fichas[y][gridx-1]==fichas[y+1][gridx-1]&&fichas[y][gridx-1]!="#FFFFFF")//dir + "sq0.gif")
				{
					return false	
				}
	}
	return true;	
}

	
function caer(y,x) {
	if(y==0)
		fichas[y][x] = "#FFFFFF"//dir + "sq0.gif";
	else{
		fichas[y][x] = fichas[y-1][x];
		caer(y-1,x)
	}
}

//Mueve las columnas a la izquierda para rellenar el hueco
function moverColumnas(y,x) {
	if(x==0)
		fichas[y][x] = "#FFFFFF"//dir + "sq0.gif";
	else
		fichas[y][x] = fichas[y][x-1];
		
	if(y!=0)
		moverColumnas(y-1,x);
}


// Recursive function to 'move' the grid
function rearrangeGrid() {
	var x, y;
	for(x = 0; x < gridx; ++x) {
		 for(y = 0; y < gridy; ++y){
			if(fichas[y][x]== "#D6D3CE")//dir + "nomine.gif")
				caer(y,x);		
		}
	}
	
	for(x = 0; x < gridx; ++x) {	
		if(columnaVacia(x))
			for(r = x; r >=0; --r)
				moverColumnas(gridy-1,r);
	}	
}

function foto() {
	
	divMarcoTablero.setContent(codigoDelTablero(false))
		/*
	
	for(y = 0; y < gridy; ++y) {
		for(x = 0; x < gridx; ++x) {
			document.images["grd"+y+"_"+x].src=fichas[y][x];
		}
	}*/
}

function columnaVacia(x) {
	var y;
	for(y = 0; y < gridy; ++y) {
		if(fichas[y][x]!="#FFFFFF")//dir +"sq0.gif")
			return false;
	}
	return true;
}

// handler called whenever the grid is clicked
function gridclick(y,x) {

	imagenOrig=fichas[y][x];
	if (imagenOrig!="#FFFFFF"){//dir + "sq0.gif" ){
		Auxsquaresleft=squaresleft;
		//para el undo
		copiar(fichas,fichasOld);
		squaresleftOLD=squaresleft;
		scoreOLD=score;
		u++
		
		rollback(y,x);
		squaresDeleted=Auxsquaresleft-squaresleft;
		if(squaresDeleted==1)
		{
			fichas[y][x]=imagenOrig;
			squaresleft++
			myLayer = new JSFX.Layer(JSFX.findLayer("mensajes"));
			myLayer.setContent("<table><tr><td nowrap><font size=2>Prueba en otro</font></td></tr></table>")	
		}
		else
		{
			undo=true;
			out('undo')
			rearrangeGrid();
			if(scoreTipe=="highscore")
				score=score+squaresDeleted+(squaresDeleted-2)*(squaresDeleted-2);
			else
				score=squaresleft;
			
			divMensajes.setContent("&nbsp;")
			divRestan.setContent("<table><tr><td nowrap><font size=2>"+squaresleft+"</font></td></tr></table>")
			divPuntuacion.setContent("<table><tr><td nowrap><font size=2>"+score+"</font></td></tr></table>")
		}
	}
	foto();
	if (finalizado()){
		divMensajes.setContent("<table><tr><td nowrap><font size=2>"+"El juego ha finalizado"+"</font></td></tr></table>")
		
		/*enviar=confirm("¿Desea enviar el resultado?")
		if (enviar){
			while(email==""||email=="null"){
				email=prompt("Debe de introducir su email.En preferencias tiene esa opción","")
			}
			alert("xx"+email+"xx")
			fr=document.fresultado;
			fr.identificador.value=email;
			fr.resultado.value=score;
			fr.tipo.value=scoreTipe;
			fr.submit();
		}*/
	}
}

