// 
// AJAX & FUNCTIONS
// LPMETHOD GAME v1.0
// Copyright 2009 Creativat Multimedia - http://www.creativat.com
//

// FUNCION CAMBIAR FONDO COLOR
function gmCanviaFons(imgFons) {
	$("#game1, #game2").fadeTo('normal', 0, function(){
		$("#juego").removeClass().addClass(imgFons);
		$("#footerFons").attr("src", "game/img/bottom-"+imgFons+".png");
		$("li.colorLateral").fadeIn('def');
		$("#lateral-"+imgFons).hide();
		$("#game2").fadeTo('normal', 1);
	});
	
	$.post('./game/ajax/ajax.proc.php', 'accion=sessioncolor&color='+imgFons,
		function (resp) {
		}, "json");	
}

function tancaJoc() {
	$("#fondo_opaco").addClass("desaparece");
	$('#juego').hide('slow');
}
function gmCanviaFonsLogin(imgFons) {
	$("#game1").fadeTo('normal', 0, function(){
		$("#juego").removeClass().addClass(imgFons);
		$("#footerFons").attr("src", "game/img/bottom-"+imgFons+".png");
		$("#colorsIntro li").fadeIn('def');
		$("#login-"+imgFons).hide();
		$("li.colorLateral").show();
		$("#lateral-"+imgFons).hide();
		$("#game1").fadeTo('normal', 1);
	});
	
	$.post('./game/ajax/ajax.proc.php', 'accion=sessioncolor&color='+imgFons,
		function (resp) {
		}, "json");	
}


function gmLogin() {
	//var mrwUser = $("#user").val();
	//var mrwPass = $("#pass").val();
	var datos = $("#logLP").serialize();
	$.post('./game/ajax/ajax.proc.php', 'accion=login&'+datos,
		function (resp) {
			if (resp==1) {
				//$("#game1").hide('slow', function() {
				//	$("#game2").show('slow');
				//});
				$('#mrwLoginKO').html('<font style="color:green; font-weight:bold;">OK. Enjoy!');
				//top.location.href = '?m=11';
				top.location.href = $("#params").val();
			}
			else {
				$('#mrwLoginKO').text('This username does not exist or the password is incorrect');
			}
		}, "json");
}

// FUNCION CATEGORIAS
function categoria(categoriaID, leyendaCat) {
	$.post('./game/ajax/ajax.proc.php', 'accion=consultaEstado',
					function (resp) {
						if (resp[0]==1 || resp[1]==1) {
							$("#mTest").hide();
						}
					}, "json");
	
	if (categoriaID==0) {
		$.post('./game/ajax/ajax.proc.php', 'accion=categorias&categoriaID='+categoriaID,
		function (resp) {
			$("#divCategorias").hide()
			.html(resp)
			.fadeIn('slow');
			$("li.subCategoria").hide();	
		}, "json");
	}
	else {
		//$("#leyendaPunto1").hide();
		//$("#leyendaCat").hide();
		
		$("#leyendaPunto1").show();
		$("#leyendaCat").attr("href", "?m=11&llegendaId="+categoriaID+"&llegendaCat="+leyendaCat)
		.text(leyendaCat.replace("@", "&"))
		.show();
		$("li.subCategoria").hide();
		$("li.subCategoria.cat"+categoriaID).fadeIn('def');
		$("#categoria a.marcado").removeClass();
		$("#catBloc"+categoriaID).addClass("marcado");
	}	
}
nivelDemo="";
function categoria_demo(categoriaID, leyendaCat, nivel) {
nivelDemo=nivel;
	$.post('./game/ajax/ajax.proc.php', 'accion=consultaEstado',
					function (resp) {
						if (resp[0]==1 || resp[1]==1) {
							$("#mTest").hide();
						}
					}, "json");
	
	if (categoriaID==0) {
		$.post('./game/ajax/ajax.proc.php', 'accion=categorias_demo&categoriaID='+categoriaID+'&nivel='+nivel,
		function (resp) {
			$("#divCategorias").hide()
			.html(resp)
			.fadeIn('slow');
			$("li.subCategoria").hide();
			$("#entradillaDemo").hide();
			$("#entradillaDemo3").show();
		}, "json");
	}
	else {
		//$("#leyendaPunto1").hide();
		//$("#leyendaCat").hide();
		
		$("#leyendaPunto1").show();
		$("#leyendaCat").attr("href", "?m=11&llegendaId="+categoriaID+"&llegendaCat="+leyendaCat)
		.text(leyendaCat.replace("@", "&"))
		.show();
		$("li.subCategoria").hide();
		$("li.subCategoria.cat"+categoriaID).fadeIn('def');
		$("#categoria a.marcado").removeClass();
		$("#catBloc"+categoriaID).addClass("marcado");
	}	
}

function categoriaLeyenda(categoriaID, leyendaCat) {
	$("#leyendaPunto1").show();
	$("#leyendaCat").attr("href", "?m=11&llegendaId="+categoriaID+"&llegendaCat="+leyendaCat.replace("&amp;", "@"))
	.html(leyendaCat)
	.show();

	$.post('./game/ajax/ajax.proc.php', 'accion=categorias&categoriaID='+categoriaID,
		function (resp) {
			$("#divCategorias").hide()
			.html(resp)
			.fadeIn('slow');
			$("li.subCategoria").hide();	
			$("li.subCategoria").hide();
			$("li.subCategoria.cat"+categoriaID).fadeIn('def');
			$("#categoria a.marcado").removeClass();
			$("#catBloc"+categoriaID).addClass("marcado");
}, "json");
		//$("#leyendaPunto1").hide();
		//$("#leyendaCat").hide();
}


// FUNCION ABRIR JUEGO
var juegoID = "";
var tipoID = "";
var abierto = "no";
function obreJoc(oJjuegoID, oJtipoID, leyendaJuego, esDemo, nivelDemo) {
	$.post('./game/ajax/ajax.proc.php', 'accion=estaLogueado',	
	function (resp) {
		if (resp=='OK') {
			juegoID = oJjuegoID;
			tipoID = oJtipoID;
			if (abierto=="no") {
				switch(juegoID) {
					case 4:
					case 15:
						cuant_temps = 2;
						break;
					case 1:
					case 6:
					case 3:
					case 8:
						cuant_temps = 3;
						break;
					case 9:
					case 11:
					case 13:
					case 16:
					case 18:
					case 19:
					case 4:
						cuant_temps = 4;
						break;
					case 7:
					case 14:
					case 2:
					case 12:
					case 25:
						cuant_temps = 5;
						break;
					case 10:
					case 5:
						cuant_temps = 10;
						break;
					default:
						cuant_temps = 5;
				}				
				$.getScript("./game/ajax/jquery.countr.js");
				abierto = "si";
				$.getScript("./game/ajax/juegos/juego-"+tipoID+".js", function(){
					cargaEstructura('no');
					if (esDemo=="demo") {
						$("#entradillaDemo").hide();
						$("#entradillaDemo2").show();
						$("#footDemo").hide();
						botoStart("demo", 30 * 1000, nivelDemo, 1);
					}					
				});
				$("#leyendaPunto2").show();
				$("#leyendaSubCat").html('&nbsp;').html('<u>'+leyendaJuego+'</u>').show();
				$("#mrwZonaFinal").text(leyendaJuego);
			
				$.post('./game/ajax/ajax.proc.php', 'accion=abrirJuego&juegoID='+juegoID+'&tipoID='+tipoID,
				function (resp) {			
					$("#time").val(cuant_temps);
					
					$("#tiuloSec").text(resp[0]);
					$("#textoObjective").html(resp[1]);
					$("#textoReminder").html(resp[2]);
					$("#textoInstructions").html(resp[3]);
					$("#tipoID").attr("value", resp[4]);
					$("#imatgeFons"+tipoID).attr("src", "game/img/fondos/"+resp[5]);
					if (tipoID==6) {
						$("#imatgeFons6_2").attr("src", "game/img/fondos/"+resp[8]+".gif");
						$("#qOir").removeClass();
						$("#qOir").addClass(resp[8]);
					}
					$("#level").html(resp[6]);
					$("#set").html(resp[7]);
				}, "json");
			}
		}
		else {
			top.location.href = '?m=11';
		}
	}, "json");
}

// FUNCION PARA OBTENER SETS DISPONIBLES SEGUN NIVEL
function obtenerSets() {
nivelSeleccionado = $("#level").val();
$.post('./game/ajax/ajax.proc.php', 'accion=obtenerSets&juegoID='+juegoID+'&tipoID='+tipoID+'&nivel='+nivelSeleccionado,
		function (resp) {
			$("#set").html(resp[0]);
		}, "json");
}

// FUNCION ABRIR CERRAR ROI's

function canviaRoi(roi) {
	$("#objective, #reminder, #instructions").hide('def');
	$("#"+roi).show('def');
	
	$("#mObjective, #mReminder, #mInstructions").removeClass();
	$("#m"+ucfirst(roi)).addClass("marcado");
}

// FUNCION PARA SUMAR EL TIEMPO REQUERIDO DE TIMEOUT
function tiempoReq(que) {
	var valorTime = parseInt($("#time").val());
	if (que=="suma") {
		if (valorTime<30) $("#time").attr("value", valorTime + 1);
	}
	if (que=="resta") {
		if (valorTime>1) $("#time").attr("value", valorTime - 1);
	}
}

// FUNCIONALIDADES ABRIR SECCIONES
tiempo_restante = "";
tiempo_restante_next = "";
var testCargado = false;
function abrirSeccion(sec, leyendaSec) {
if (tiempo_restante!="") tiempo_restante.stop();
if (tiempo_restante_next!="") tiempo_restante_next.stop();
$("#menuROI, #divPuntuacio, #reminder, #objective, #instructions, #tipo1, #tipo2, #tipo3, #tipo4, #tipo5, #tipo6, #tipo7, #tipo8, #tipo9, #categoria, #divMystats, #divLptest, #divMistakes, #final, #divLptestInicio, #lpTestAprobado, #lpTestSuspendido, #divLptestMistakes, #lpTestQuests").hide('def');
$("#mStart, #mMyStats, #mMistakes, #mTest, #mManual, #mLanguage").removeClass("marcado");

$("#leyendaPunto1, #leyendaCat").hide();
$("#leyendaPunto2, #leyendaSubCat").hide();

$("#leyendaPunto1, #leyendaCat").show();
$("#leyendaCat").text(leyendaSec)

	switch (sec) {
		case "startlp":
			$("#mStart").addClass("marcado");		
			$("#cateogira").show(); // PRINCIPI
			categoria(0);
			$("#tiuloSec").text("LP CATEGORIES");
			break;
		case "mystats":
			$("#mMyStats").addClass("marcado");	
			$("#divMystats").show('def');
			$("#tiuloSec").text("MY STATS");
			$("#entradillaDemo").text("Para visualizar tu evolución en las distincas zonas y niveles en el juego");
			if (demoUsuario=="demo") {
				$("#footDemo").hide();
			}
			//mystatsBars();
			break;
		case "lptest":
			$("#mTest").attr("onclick", "");
			$("#mTest").addClass("marcado");	
			$('#divLptest, #inicioTest').show('def');
			$("#tiuloSec").text("LP TEST");
			$("#entradillaDemo").text("Para hacer únicamente los ejercicios que correspondan a tu nivel");
			//if (testCargado==false) {
			$.getScript("./game/ajax/lptest.js");
			//}
			if (demoUsuario=="demo") {
				$("#footDemo").hide();
			}			
			break;
		case "lpmanual":
			break;
		case "language":
			break;
	}
}

// ABRIR/CERRAR DIV IDIOMAS
function obrirIdioma() {
	$("#idiomes").toggle('fast');
}


// APLICA EFECTO RELLENO BARRAS DE PROGRESO NIVEL
function mystatsBars() {
	cuantasProgress = $('img.progressBar').size();
	tiempo_mystats = $.timer(2000, function (timer) {
		tiempo_mystats.stop();
		for (i=1;i<=cuantasProgress;i++) {
			numeroRand = rand(1, 100);
			//console.log("#progressBar"+i);
			//$("#percentatge"+i).text(numeroRand+"%").fadeIn(1500);
			/*$("#progressBar"+i).animate({
				width: numeroRand+"%"
			}, 1400);*/
		}
	});
}

// VER DETALLES Y BOTON ATRAS
function myStats(que) {
	switch (que) {
		case "atras":
			$("#mystatsdetalles").hide('def');
			$("#mystatsbars").show('def');
			abajo = "";
			break;
	}
}

function verDetallesStats(usuarioID, categoriaID, juegoID, nivel) {
	//alert(usuarioID+", "+categoriaID+", "+juegoID+", "+nivel);
	$.post('./game/ajax/ajax.proc.php', 'accion=detalleStats&usuarioID='+usuarioID+'&categoriaID='+categoriaID+'&juegoID='+juegoID+'&nivel='+nivel,
				function (resp) {
					$("#mystatsdetalles").html(resp);
					$("#lvlMystatsDetalle").html(nivel);

	$.post('./game/ajax/score.proc.php', 'accion=puntosxjuegoynivel&juegoID='+juegoID+'&nivel='+nivel,
					function (resp) {
						$("#globalScoreDetalles").html(resp[0]+" / 1000");
					}, "json");	
				}, "json");

	$("#mystatsdetalles").show('def');
	$("#mystatsbars").hide('def');
}

function lptest() {
	lpTestStart();	
}

//////////////////////////////////////////////////
//               FUNCIONES REGISTROS BDD
//////////////////////////////////////////////////

var dbSesionID="";
function dbInicioSesion() {
	if (demoUsuario!="demo") {
		$.post('./game/ajax/ajax.proc.php', 'accion=inicioSesion&juegoID='+juegoID+'&nsets='+sets+'&nivel='+nivel+'&time_request='+timeout,
					function (resp) {
						dbSesionID = resp[0];
					}, "json");
	}
}

function dbFinalSesion() {
	if (demoUsuario!="demo") {
		$.post('./game/ajax/ajax.proc.php', 'accion=finalSesion&sesionID='+dbSesionID,
		   function() {
				$.post('./game/ajax/score.proc.php', 'accion=puntosxjuegoynivel&juegoID='+juegoID+'&nivel='+nivel,
									function (resp) {
										if (resp[0]==1000) $("#entradillaFinalSesion").hide();
										$("#puntsTotalT").text(resp[0]);
										$("#puntsTotal").text(resp[0]);
										$("#mrwLevelFinal").text(nivel);
									}, "json");
		   });
	
/*$.post('./game/ajax/score.proc.php', 'accion=puntosxjuegoynivel&juegoID='+juegoID+'&nivel='+nivel,
					function (resp) {
						$("#puntsTotalT").text(resp[0]);
						$("#puntsTotal").text(resp[0]);
					}, "json");*/
	}
}

function dbFinalSet() {
	StopStartTimer();
	if (demoUsuario!="demo") {
	//$.post('./game/ajax/ajax.proc.php', 'accion=finalSet&sesionID='+dbSesionID+'&score='+score);
	$.post('./game/ajax/score.proc.php', 'accion=controlscore&juegoID='+juegoID+'&nivel='+nivel+'&score='+score+'&sesionID='+dbSesionID+'&sesion_finalizada='+controlSets,
		   function (resp) {
						$("#textoFinalSesion").html(resp[3]);
						$("#puntsFinalT").text(resp[5]);
						if (resp[4]==0) {
							$("#entradillaFinalSesion").hide();
						}
						if (resp[1]==1 || resp[2]==1) {
							$("#divMistakes, #divPuntuacio, #tipo"+tipoID).hide();
							$("#final").show('slow');						
							// PONER AQUI COMPROBACION DE SI PUNTUA O NO (PUNTUCION MINIMA) PARA ASI RESTAR AL TOTALSCORE LA PUNTUACION REALIZADA EN ESE SET QUE NO DEBERIA SUMARSE
							// totalscore = totalscore - score;
						}
					}, "json");
	}
	if (demoUsuario=="demo") {
		$("#footDemo").show();
	}	
}

var abajo = "";
function scrollUpDetalles() {
	if (abajo=="") {
		var mydiv = document.getElementById("listadoStats");
		abajo = "si";
		mydiv.scrollTop = mydiv.scrollHeight - mydiv.clientHeight;
	}
}

var running = false;
function showProgressDots(numberOfDots) {
    if (running) {
		switch(numberOfDots) {
			case 1:
				$("#textQ").html('<p class="loader">loading .</p>');
				timerHandle = setTimeout('showProgressDots(2)',200);
				break;
			case 2:
				$("#textQ").html('<p class="loader">loading ..</p>');
				timerHandle = setTimeout('showProgressDots(3)',200);
				break;
			case 3:
				$("#textQ").html('<p class="loader">loading ...</p>');
				timerHandle = setTimeout('showProgressDots(1)',200);
				break;
		}
	}
}

function StopStartTimer() {
   if (running) {
      running=false;
   }
   else {
      running=true;
      window.setTimeout('showProgressDots(1)',100);
   }
}

//////////////////////////////////////////////////

//
// FUNCIONES EXTRA
//

function ucfirst( str ) {
    str += '';
    var f = str.charAt(0).toUpperCase();
    return f + str.substr(1);
}

function strtoupper( str ) {
    return (str+'').toUpperCase();
}

function rand( min, max ) {
    var argc = arguments.length;
    if (argc == 0) {
        min = 0;
        max = 2147483647;
    } else if (argc == 1) {
        throw new Error('Warning: rand() expects exactly 2 parameters, 1 given');
    }
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

shuffle = function(o){ //v1.0
	for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
	return o;
};