var arrayDuracionEstandar = new Array (
"10","10 preguntas",
"20","20 preguntas",
"30","30 preguntas",
"40","40 preguntas",
"50","50 preguntas",
"100","100 preguntas" )

var arrayDuracionContrarreloj = new Array (
"300","5 minutos",
"600","10 minutos",
"900","15 minutos",
"1200","20 minutos",
"1800","30 minutos",
"3600","60 minutos" )

var iTimerID;

// Función que se ejecuta en el onload de todas las páginas. Inicializa el timer en las páginas de tipo test.
//-----------------------------------------------------------------------------------------------------------
function initPagina(tipo, reto, msg, modo, numPregunta) {
	if (tipo.substr(0, 1)  == "T" && numPregunta != "") {
		if (modo == "C") iTimerID = window.setTimeout("temporizador_dec()", 1000);
    	else iTimerID = window.setTimeout("temporizador_inc()", 1000);
    }
	if (msg != "") alert(msg);
	if (reto > 0) blink('img_reto');
	initmb();
}


//Si pulsamos una opción que provocaría que se cancelara el test en curso, avisamos.
//----------------------------------------------------------------------------------
function cancelarTest(estado) {
	if (estado != "") return window.confirm("Esta acción finalizará el test que estas realizando.\r ¿Deseas finalizar el test?");
	else return true;
}


function temporizador_inc() { temporizador("E"); }

function temporizador_dec() { temporizador("C"); }


// FUNCIONES TEMPORIZADOR INI	
function temporizador(modalidadTest) {
	v_totalTiempoTest = document.getElementById("totalTiempoTest");

	if (modalidadTest == "C") v_totalTiempoTest_value = parseInt(v_totalTiempoTest.value) - 1;
	else v_totalTiempoTest_value = parseInt(v_totalTiempoTest.value) + 1;
	v_totalTiempoTest.value = v_totalTiempoTest_value;
	v_minutos = Math.floor(v_totalTiempoTest_value/60);
	v_segundos = Math.round(v_totalTiempoTest_value - (v_minutos*60));
	if (v_segundos<10) v_segundos = "0" + v_segundos;
	document.getElementById("totalTiempoTest_format").value = v_minutos + ":" + v_segundos;
	
	v_tiempoPregunta = document.getElementById("tiempoPregunta");
	v_tiempoPregunta_value = parseInt(v_tiempoPregunta.value) - 1;
	v_tiempoPregunta.value = v_tiempoPregunta_value;
	v_minutos = Math.floor(v_tiempoPregunta_value/60);
	v_segundos = Math.round(v_tiempoPregunta_value - (v_minutos*60));
	if (v_segundos<10) v_segundos = "0" + v_segundos;
	document.getElementById("tiempoPregunta_format").value = v_minutos + ":" + v_segundos;

	// Si se excede el tiempo de la pregunta o del test, pasamos a la siguiente.
	if (v_tiempoPregunta_value <= 0 || v_totalTiempoTest_value <= 0) {
		document.getElementById("respuestaPregunta").value="?";  // Mostrar solucion y pasar a la siguiente
		//if (v_totalTiempoTest_value <= 0) document.getElementById("formularioRespuesta").action = "fintest.asp"
		window.clearTimeout(iTimerID);
		sm("box",200,50);
		document.getElementById("formularioRespuesta").submit();

	// Si no hemos llegado al límite de tiempo, lanzamos de nuevo el temporizador.
	} else {
	    if (modalidadTest == "C") iTimerID = window.setTimeout("temporizador_dec()", 1000);
	    else iTimerID = window.setTimeout("temporizador_inc()", 1000);
	}
}

function formatearMensajeTiempo(hora_inicio, hora_fin) {
	if (hora_inicio != 0) {
		total_tiempo = hora_fin - hora_inicio;
		horas = Math.round(total_tiempo/1000/60/24);
		total_tiempo = total_tiempo - (horas*1000*60*24);
		minutos = Math.round(total_tiempo/1000/60);
		total_tiempo = total_tiempo - (minutos*1000*60);
		segundos = Math.round(total_tiempo/1000);
		mensaje = "Has empleado ";
		if (horas > 0) mensaje = mensaje + horas + " horas ";
		if (minutos > 0) mensaje = mensaje + minutos + " minutos ";
		if (segundos > 0) mensaje = mensaje + segundos + " segundos ";
		mensaje = mensaje + "en resolver el test.\r";
	} else mensaje = "";
	return mensaje;
}
// FUNCIONES TEMPORIZADOR FIN


// FUNCIONES BOTONERA INI
//Pressed 
function changeImage(btn,tam)
{
  if (tam=="p") btn.style.backgroundPosition = "0px 114px"; //45
  else if (tam=="m") btn.style.backgroundPosition = "0px 240px";
  else btn.style.backgroundPosition = "0px 240px";
  btn.style.paddingTop = "0px";
  btn.style.paddingLeft = "0px";
  return true;
}

//Normal --
function changeImageBack(btn,tam) 
{
  btn.style.backgroundPosition = "0px 0px";
  btn.style.paddingTop = "0px";
  btn.style.paddingLeft = "0px";
   return true;
}
//Hover
function handleMDown(btn,tam)
{
  if (tam=="p") btn.style.backgroundPosition = "0px 57px"; //23
  else if (tam=="m") btn.style.backgroundPosition = "0px 120px";
  else btn.style.backgroundPosition = "0px 120px";
  btn.style.paddingTop = "0px";
  if (self.navigator.appName.indexOf('Microsoft Internet Explorer') >= 0) btn.style.paddingLeft = "0px";
  else btn.style.paddingLeft = "0px";
  return true;
}
function handleMUp(btn,tam)
{
	changeImage(btn,tam);
	return true;
}
// FUNCIONES BOTONERA FIN



//Carga los datos de un array en una lista desplegable. Deja seleccionado el que se le indica.
//--------------------------------------------------------------------------------------------
function cargarSelect (selectObj, arrayDatos, sel) {
	var totalDatos = arrayDatos.length;
	var selIndex = 0;
	borrarSelect(selectObj, "N");
	for (i=0;i<totalDatos;i=i+2) {
		selectObj.options[i/2] = new Option(arrayDatos[i+1],arrayDatos[i]);
		if (sel == arrayDatos[i]) selIndex = i/2;
	}
	selectObj.selectedIndex = selIndex;
}


//Borra los datos de una lista html. Todos menos el primero.
//----------------------------------------------------------
function borrarSelect(selectObj, newOpt){
	var totalDatos = selectObj.length;
	while(totalDatos >= 0) selectObj.remove(totalDatos--);
	if (newOpt == "S") selectObj.options[0] = new Option("Sin especificar","");
}


//Obtiene la posición de un elemento de la página.
//------------------------------------------------
function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;	
		} while (obj = obj.offsetParent);
	}
	return [curleft,curtop];
}


// Hace parpadear un objeto.
//-------------------------
function blink(id) {
	var e = document.getElementById(id);
    e.style.visibility = ( e.style.visibility == 'visible' )? 'hidden' : 'visible';
    setTimeout("blink('" + id + "');", 500);
}

function aceptarReto(idReto) {
	if (confirm("¿Desea aceptar el reto seleccionado y comenzar el test?")) {
		location.href="consulta-retos.asp?idReto=" + idReto + "&aceptar=S";
	}
}

function rechazarReto(idReto) {
	if (confirm("¿Desea rechazar el reto seleccionado?")) {
		location.href="consulta-retos.asp?idReto=" + idReto + "&aceptar=N";
	}
}


//Comprueba que estén informados los datos obligatorios del formulario de alta.
//-----------------------------------------------------------------------------
function validarDatosConexion() {
	var codigo = document.getElementById("CIT_USER_codigo");
	var clave = document.getElementById("CIT_USER_clave");
	codigo.style.backgroundImage="url(img/bg_user.png)";
	clave.style.backgroundImage="url(img/bg_pas.png)";
	if (codigo.value == "") {
		codigo.style.backgroundImage="url(img/bg_user_error.png)";
		codigo.focus();
		alert("Es obligatorio informar el código de usuario.");
		return false;
	} else if (clave.value == "") {
		clave.style.backgroundImage="url(img/bg_pas_error.png)";
		clave.focus();
		alert("Es obligatorio informar el password.");
		return false;
	}
	return true;
}

//Validar que el formato de fecha sea correcto.
//---------------------------------------------
function validarFecha(fechaIn) {
    try {
        fechaSplit = fechaIn.split("/");
        var fecha = new Date(fechaSplit[0],fechaSplit[1],fechaSplit[2]);
        return !isNaN(fecha.getTime());
    } catch(e) {alert(false);return false;}
}

// Limitar el número de caracteres de un textarea.
//------------------------------------------------
function limitText(limitField, limitCount, limitNum) {
	if (limitField.value.length > limitNum) {
		limitField.value = limitField.value.substring(0, limitNum);
	} else {
		limitCount.value = limitNum - limitField.value.length;
	}
}

//Al cambiar el tipo de test, actualiza las posibles duraciones.
//--------------------------------------------------------------
function cambiarListaDuracion(idtipo,duracion) {
	var destino = document.getElementById(duracion);
	var tipoSel = idtipo.options[idtipo.selectedIndex].value;
	if (tipoSel == "E") {
		destino.disabled = false;
		cargarSelect (destino, arrayDuracionEstandar, "40");
	} else if (tipoSel == "C") {
		destino.disabled = false;
		cargarSelect (destino, arrayDuracionContrarreloj, "1200");
	} else if (tipoSel == "F") {
		destino.disabled = true;
	}
}

// Validamos la cadena para permitir únicamente caracteres alfanuméricos.
//-----------------------------------------------------------------------
function validText(str){ 
    return str.replace(/[^a-zA-Z0-9]/g,''); 
} 

// Validamos la cadena para permitir únicamente caracteres alfanuméricos.
//-----------------------------------------------------------------------
function inputValidText(obj){
	valorAnterior = obj.value;
	valorNuevo = valorAnterior.replace(/[^a-zA-Z0-9]/g,'');
    if (valorNuevo != valorAnterior) {
		obj.value = valorNuevo;
    	alert("Únicamente se permiten caracteres alfanuméricos [A-Z], [a-z], [0-9] en este campo.");
    }
} 


// Validamos la cadena para permitir únicamente caracteres numéricos.
//-------------------------------------------------------------------
function inputValidNumber(obj){
	valorAnterior = obj.value;
	valorNuevo = valorAnterior.replace(/[^0-9,]/g,'');
    if (valorNuevo != valorAnterior) {
		obj.value = valorNuevo;
    	alert("Únicamente se permiten caracteres numéricos [0-9] y la coma \",\" decimal en este campo.");
    }
} 


// Validamos la cadena para permitir únicamente caracteres numéricos.
//-------------------------------------------------------------------
function inputValidIntNumber(obj){
	valorAnterior = obj.value;
	valorNuevo = valorAnterior.replace(/[^0-9]/g,'');
    if (valorNuevo != valorAnterior) {
		obj.value = valorNuevo;
    	alert("Únicamente se permiten caracteres numéricos [0-9] en este campo.");
    }
} 


