/** FUNCIONES JAVASCRIPT **/

/*Redirección al cerrar sesión*/
function redirecciona() {
//location.href="http://localhost/cttripollet/cat/portada.php";
location.href="http://cttripollet.org/cat/portada.php";
}
/***** Funciones para VALIDACIÓN DE FORMULARIOS
function ok() {
	return true;
} ******/

function logout() {
	alert("Gràcies per la seva visita.");
	return true;
}

//VALIDAR FORMULARIO DE REGISTRO
function valida_registro() {

	var vnick=document.getElementById("usuario").value;
	var vpass=document.getElementById("password").value;
	var vpass2=document.getElementById("password2").value;
	var vemail=document.getElementById("email").value;
	var vnom=document.getElementById("nom").value;
	var vcogs=document.getElementById("cogs").value;
	
	//campos obligatorios
	if (vnick=="" || vpass=="" || vpass2=="" || vemail=="" || vnom=="" || vcogs==""){
		alert("Tots els camps son obligatoris");
		return false;	
	} else {
		//tamaño del nick
		if (vnick.length<3 || vnick.length>10) {
			alert("El nom d'usuari ha de tenir entre 3 i 10 caràcters");
			return false;
		}
		//formato nick (alfanumerico sin espacios)
		var expreg= /^(\w+|\S)$/;   
		if(!expreg.test(vnick)) {
			alert("El nick només pot estar format per caràcters alfanumèrics o '_', però no accepta espais");
			return false;
		}
		//tamaño password
		if (vpass.length<4 || vpass.length>15) {
			alert("La contrasenya ha de tenir entre 4 i 15 caràcters");
			return false;
		}

		//passwords iguales
		if(vpass!=vpass2) {
			alert("Les contrasenyes introduides no coincideixen");
			return false;
		}
		//validar e-mail
		/*if (isEmailAddress(vemail) == false) {
				alert("El format d'e-mail introduit no es correcte");
				return false;
		}*/
		
		//formato nom y cognoms (alfanumérico con espacios)
		if (validarNom(vnom)==false || validarNom(vcogs)==false) {
				alert("El nom o cognoms introduits té algun caràcter invàlid");
				return false;			
		}
		return true;
	}

}

//VALIDAR FORMULARIO DE LOGIN
function valida_login() {

	var vnick=document.getElementById("nick").value;
	var vpass=document.getElementById("pass").value;

	//campos obligatorios
	if (vnick=="" || vpass==""){
		alert("Tots els camps son obligatoris");
		return false;	
	}
	return true;
}

//VALIDAR FORMULARIO DE SOCIOS
function valida_socio() {

	var vnom=document.getElementById("nom").value;
	var vcog1=document.getElementById("cognom1").value;
	var vcog2=document.getElementById("cognom2").value;
	var vdoc=document.getElementById("doc").value;
	var vcatsalut=document.getElementById("catsalut").value;
	var vcp=document.getElementById("cp").value;
	//var vdir=document.getElementById("dir").value;
	var vpobl=document.getElementById("poblacio").value;
	var vnacion=document.getElementById("nacion").value;
	var vtfix=document.getElementById("telfix").value;
	var vtmov=document.getElementById("telfmov").value;
	var vemail=document.getElementById("email").value;
	var vnpers=document.getElementById("numpers").value;
	var vnfctt=document.getElementById("numfctt").value;
	var vnrfetm=document.getElementById("numrfetm").value;
	
	//campos obligatorios
	if (vnom=="" || vcog1==""){
		alert("Els camps nom i primer cognom són obligatoris");
		return false;	
	}
	
	//validar nombre y apellidos
	if (validarNom(vnom)==false || validarNom(vcog1)==false || validarNom(vcog2)==false ) {
		alert("Algun caràcter del nom o cognoms no és vàlid");
		return false;	
	}
	//validar DOC
	if (vdoc!="") {
		var expreg=/^(\w+|\s)*$/; 
		if(!expreg.test(vdoc) || vdoc.length!=9) {
			alert("El camp Doc ha d'estar format per 9 caràcters alfanumèrics sense espais");
			return false;
		}
	}
	//validar CATSALUT
	var expreg=/^(\w+|\s)*$/; 
	if(!expreg.test(vcatsalut)) {
		alert("El camp de CATSALUT ha de ser alfanumèric amb o sense espais");
		return false;	
	}
	//validar CP
	if (vcp!="") {
		var expreg=/^(\d+|\s)*$/; 
		if(!expreg.test(vcp) || vcp.length!=5) {
			alert("El CP ha d'estar format per 5 caràcters numèrics de largo es "+vcp.length);
			return false;	
		}
	}
	//validar poblacion 
	if(validarNom(vpobl)==false) {
		alert("El format de la població introduida és incorrecta");
		return false;	
	}
	//validar nacionalidad
	if(validarNom(vnacion)==false) {
		alert("El format de la nacionalitat introduida és incorrecta");
		return false;	
	}
	//validar telf fijo
	if(vtfix!="") {
		if(validarTelf(vtfix)==false || vtfix.length!=9){
			alert("El camp del telèfon fixe ha d'estar omplert per 9 caràcters numèrics");
			return false;	
		}
	}
	//validar telf movil
	if(vtmov!="") {
		if(validarTelf(vtmov)==false || vtmov.length!=9){
			alert("El camp del telèfon mòbil ha d'estar omplert per 9 caràcters numèrics");
			return false;	
		}
	}
	//validar e-mail
	/*if (vemail!="") {
		if (isEmailAddress(vemail) == false) {
			alert("El format d'e-mail introduit no es correcte");
			return false;
		}
	}*/
	
	//validar numeros personales (persona, fctt, rfetm)
	var expreg=/^(\d{0,4}|\s)$/; 
	if(!expreg.test(vnpers) || !expreg.test(vnfctt) || !expreg.test(vnrfetm)) {
		alert("Algun número personal introduit no és correcte");
		return false;	
	}
	
	return true;
}

//VALIDAR FORMULARIO DE NOTICIAS
function validanoticia() {
	var vdia=document.getElementById("dia").value;
	var vmes=document.getElementById("mes").value;
	var vano=document.getElementById("ano").value;
	var vtemp=document.getElementById("temp").value;
	var vtitulo=document.getElementById("titulo").value;
	
	//campos obligatorios
	if (vdia==-1 || vmes==-1 || vano==-1) {
		alert("La data és un camp obligatori");
		return false;	
	}
	if (vtemp==-1) {
		alert("És obligatori escollir temporada");
		return false;	
	}	
	if (vtitulo=="") {
		alert("És obligatori posar un títol a la noticia");
		return false;		
	}
	return true;
	
}

//VALIDAR FORMULARIO DE COMUNICADOS
function validacomunicado() {
	var vdia=document.getElementById("dia").value;
	var vmes=document.getElementById("mes").value;
	var vano=document.getElementById("ano").value;
	var vasunto=document.getElementById("asunto").value;
	
	//campos obligatorios
	if (vdia==-1 || vmes==-1 || vano==-1) {
		alert("La data és un camp obligatori");
		return false;	
	}
	if (vasunto=="") {
		alert("És obligatori escriure un asumpte al comunicat");
		return false;		
	}
	return true;
	
}

//VALIDAR FORMULARIO DE CAMPEONATOS
function validacto() {

	var vnom=document.getElementById("nom").value;
	var vdiai=document.getElementById("diaini").value;
	var vmesi=document.getElementById("mesini").value;
	var vanoi=document.getElementById("anoini").value;
	var vpobl=document.getElementById("poblacion").value;
	var vtemp=document.getElementById("temp").value;
	var vtipo=document.getElementById("tipo").value;
	
	if (vnom==""){
		alert("Els camp del nom és obligatori");
		return false;	
	}
	if (vdiai==-1 || vmesi==-1 || vanoi==-1){
		alert("La data d'inici és obligatòria");
		return false;	
	}
	if (vpobl==""){
		alert("El camp població és obligatori");
		return false;	
	}
	if (vtemp==-1){
		alert("És obligatori seleccionar una temporada");
		return false;	
	}	
	if (vtipo==-1){
		alert("És obligatori escollir el tipus de campionat");
		return false;	
	}	
	return true;
}

//VALIDAR FORMULARIO DE LIGAS
function validaliga() {

	var vnom=document.getElementById("nom").value;
	var vsigl=document.getElementById("sigles").value;
	var venl=document.getElementById("enlace").value;
	var vniv=document.getElementById("nivel").value;
	var vtemp=document.getElementById("temp").value;
	
	//campos obligatorios
	if (vnom==""){
		alert("El camp del nom és obligatori");
		return false;	
	}
	if (vsigl==""){
		alert("El camp de les sigles és obligatori");
		return false;	
	}
	if (vniv==-1){
		alert("És obligatori seleccionar un nivell");
		return false;	
	}	
	if (vtemp==-1){
		alert("És obligatori seleccionar una temporada");
		return false;	
	}	
	//FALTA VALIDAR ENLACE
	/*if (venl!="") {
		if (validaurl(venl) == false) {
			alert("L'enllaç introduït no és vàlid");
			return false;			
		}
	}*/
		
	return true;
}

//VALIDAR FORMULARIO DE EQUIPOS
function validaequipo() {

	var vnom=document.getElementById("nom").value;
	var venl=document.getElementById("enlace").value;
	var vliga=document.getElementById("liga").value;
	var vtemp=document.getElementById("temp").value;

	//campos obligatorios
	if (vnom==""){
		alert("El camp del nom és obligatori");
		return false;	
	}
	if (vliga==-1){
		alert("És obligatori seleccionar una lliga");
		return false;	
	}
	if (vtemp==-1){
		alert("És obligatori seleccionar una temporada");
		return false;	
	}	
	
	//FALTA VALIDAR ENLACE
	/*if (venl!="") {
		if (validaurl(venl) == false) {
			alert("L'enllaç introduït no és vàlid");
			return false;			
		}
	}*/	
	return true;
}

//VALIDAR FORMULARIO DE ENCUENTROS
function validaencuentro() {

	var vjor=document.getElementById("jornada").value;
	var vdia=document.getElementById("dia").value;
	var vmes=document.getElementById("mes").value;
	var vano=document.getElementById("ano").value;
	var vhora=document.getElementById("hora").value;
	var vmins=document.getElementById("mins").value;
	var veqloc=document.getElementById("eqlocal").value;
	var veqvis=document.getElementById("eqvisit").value;
	
	//campos obligatorios
	if (vjor==-1){
		alert("Ha de seleccionar una jornada");
		return false;	
	}
	if (vdia==-1 || vmes==-1 || vano==-1) {
		alert("La data és un camp obligatori");
		return false;	
	}
	if (vhora==-1 || vmins==-1) {
		alert("És obligatori seleccionar l'hora de l'encontre");
		return false;	
	}	
	if (veqloc==-1 || veqvis==-1) {
		alert("És obligatori seleccionar l'equip local i l'equip visitant de l'encontre");
		return false;	
	}	
	//equipos diferentes
	if(veqloc==veqvis) {
		alert("L'equip local i el visitant no pot ser el mateix");
		return false;		
	}
	
	return true;
}

//VALIDAR FORMULARIO DE JUGADORES LOCALES
function validajugloc() {

	var vliga=document.getElementById("liga").value;
	var vjug=document.getElementById("jug").value;
	
	//campos obligatorios
	if (vliga==-1){
		alert("Ha de seleccionar una lliga");
		return false;	
	}
	if (vjug==-1) {
		alert("Ha de seleccionar un jugador");
		return false;	
	}
	return true;
}

//VALIDAR FORMULARIO DE JUGADORES RIVALES
function validajugriv() {

	var vnom=document.getElementsByName("nom");
	var vcog=document.getElementsByName("cog1");
	
	for(var i=0; i<vnom.length; i++) {	
		//campos obligatorios
		if (vnom[i].value == "" || vcog[i].value == ""){
			alert("Els camps nom i primer cognom són obligatoris");
			return false;	
		} else {
			/*if (validarNom(vnom)==false || validarNom(vcog)==false) {
				alert("Algun caràcter de nom o cognom introduit no és vàlid");
				return false;	
			}*/		
		}
	}
	return true;
}

//VALIDAR FORMULARIO DE PROPERA JORNADA i FORMULARIO PARA SELECCIONAR LIGA - INTRODUCIR RESULTADOS
function validaselectliga() {

	var vliga=document.getElementById("liga").value;
	
	//campos obligatorios
	if (vliga==-1){
		alert("Ha de seleccionar una lliga per poder continuar...");
		return false;	
	}
	return true;
}

//VALIDAR FORMULARIO DE INTRODUCIR RESULTADO DE UN CTO...
function validactoresult() {

	var vjug=document.getElementById("jug").value;
	var vdob=document.getElementById("dob").value;
	var veq=document.getElementById("equipo").value;
	var vcompeq=document.getElementById("compsequipo").value;
	var vcat=document.getElementById("categ").value;
	var vmod=document.getElementById("modal").value;
	var vpos=document.getElementById("pos").value;
	
	//campos obligatorios
	if (vjug==-1){
		alert("Ha de seleccionar un jugador");
		return false;	
	}
	if (vcat==-1){
		alert("Ha de seleccionar una categoria");
		return false;	
	}
	if (vmod==-1){
		alert("Ha de seleccionar una modalitat");
		return false;	
	}
	if (validarNom(vdob)==false){
		alert("El company de dobles introduït conté caràcters invàlids");
		return false;	
	}
	if (validarNom(veq)==false){
		alert("El nom d'equip introduït conté caràcters invàlids");
		return false;	
	}
	if (validarNom(vcompeq)==false){
		alert("Els components de l'equip introduïts contenen caràcters invàlids");
		return false;	
	}
	return true;
}

//VALIDAR FORMULARIO DE INTRODUCIR RESULTADO GENERAL DE UN ENCUENTRO
function validaresultenc() {

	var vrloc=document.getElementById("resloc").value;
	var vrvis=document.getElementById("resvis").value;

	//campos obligatorios
	if (vrloc=="" || vrvis==""){
		alert("Ha d'introduir els dos resultats...");
		return false;	
	}

/*if (validarInt(vrloc)==false || validarInt(vrvis)==false) {
		alert("ERROR: Ha introduït algun caràcter no-numèric");
		return false;
	}*/
	//pasar los valores a enteros
	vrloc = parseInt(vrloc);
	vrvis = parseInt(vrvis);
	if (vrloc<0 || vrloc>6 || vrvis<0 || vrvis>6) {
		alert("El resultats introduïts només poden prendre els valors de 0 a 6");
		return false;	
	}
	if (vrloc == vrvis) {
		alert("Els equips no poden haver empatat...");
		return false;	
	}
	return true;
}

//VALIDAR FORMULARIO DE INTRODUCIR/MODIFICAR ACTA
function validaacta() {

	vjugloc=document.getElementsByName("jugloc");
	vjugvis=document.getElementsByName("jugvis");
	vresloc=document.getElementsByName("resloc");
	vresvis=document.getElementsByName("resvis");
	
	for (var i=0; i<vjugloc.length; i++) {
		//Seleccionar todos los jugadores
		/*if (vjugloc[i].value == -1 || vjugvis[i].value == -1) {
			alert("No ha seleccionat tots els jugadors...");
			return false;			
		}*/
		//El jugador no puede estar repetido en el dobles (i=3) (FALTA PROBAR)
		/*if (i==3) {
			if (vjugloc[i].value == vjugloc[i+1].value || vjugvis[i].value == vjugvis[i+1].value) {
				alert("Els jugadors del dobles no poden ser el mateix...");
				return false;			
			}
		}
		//jugadores distintos en los 3 primeros individuales (0-2) y de (4+1-7+1) (el +1 es por el jugador del dobles añadido) FALTA PROBAR)
		if (i==0) {
			//equip local
			if (vjugloc[i].value == vjugloc[i+1].value || vjugloc[i+1].value == vjugloc[i+2].value || vjugloc[i].value == vjugloc[i+2].value) {
				alert("Ha repetit algun jugador de l'equip local en els tres primers individuals...");
				return false;			
			}
			//equip visitant
			if (vjugvis[i].value == vjugvis[i+1].value || vjugvis[i+1].value == vjugvis[i+2].value || vjugvis[i].value == vjugvis[i+2].value) {
				alert("Ha repetit algun jugador de l'equip visitant en els tres primers individuals...");
				return false;			
			}
		}*/
	}
	
	/*for (var i=0; i<vresloc.length; i++) {
		//resultados de cada partido obligatorios
		if (vresloc[i].value=="" || vresvis[i].value=="") {
			alert("És obligatori omplir el resultat de tots el partits...(els parcials són opcionals)");
			return false;			
		}
	
	}*/

	return true;
}

//VALIDAR CAMBIO CONTRASEÑA
function valida_cambiopass() {

	var vpassa=document.getElementById("passant").value;
	var vpassn=document.getElementById("passnew").value;
	var vpassn2=document.getElementById("passnew2").value;

	//campos obligatorios
	if (vpassa == "" || vpassn == "" || vpassn2 == "") {
		alert("Tots els camps del formulari són obligatoris");
		return false;
	}	
	//tamaño password
	if (vpassn.length<4 || vpassn.length>15) {
		alert("La nova contrasenya ha de tenir entre 4 i 15 caràcters");
		return false;
	}
	//passwords iguales
	if(vpassn!=vpassn2) {
		alert("Les noves contrasenyes introduides no coincideixen");
		return false;
	}
	
	return true;
}

//VALIDAR e-mail
function isEmailAddress(email) {
	var e = email.value;
	var expreg=/^[A-Za-z0-9_]+@[A-Za-z0-9_]+.[A-Za-z0-9_.]+[A-za-z]$/;
	if (expreg.test(e)) return true;
	else return false;
}

//VALIDAR numero entero
function validarInt(entero){
	var e = entero.value;
	e = parseInt(e);
	//si es un número
	if(isNaN(e)==false) return true;
	//si no es un número...
	else return false;
}

//VALIDAR un nom, cognoms, poblacion, nacionalidad
function validarNom(nom){
	var n = nom.value;
	var expreg=/^(\D+|\s)*$/; 
	if (expreg.test(n)) {
		return true;
	} else {
		return false;
	}
}

//VALIDAR telefono
function validarTelf(telf){
	var t = telf.value;
	var expreg=/^(\d|\S)*$/; 
	if (expreg.test(t)) return true;
	else return false;
	
}

//VALIDAR URLs
function validaurl(url) {
	var u = url.value;
	var expreg=/^http:\/\/\w+(\.|\w+)*\.\w{2,3}$/;
	//var expreg=/^http:\/\/\w+(\.\w+)*\.\w{2,3}$/;
	if (expreg.test(u)) return true;
	else return false;
} 

//VALIDAR Fecha
function validarFecha(dia,mes,ano) {

	//pasamos todos los parámetros a int
	var diaint = parseInt(dia);	
	var mesint = parseInt(mes);
	
	//VALIDAR MESES
	if (mesint>12) return false;
	// mes febrero
	if(mesint == 2){
		if(esBisiesto(ano)){
			if(diaint > 29) return false;
			else return true;
		} else{
			if(diaint > 28) return false;
			else return true;
		}		
	}
	//resto de meses
	if(mesint == 4 || mesint == 6 || mesint == 9 || mesint == 11){
		if(diaint > 30) return false;
	}
	return true;
}

//Determina si un año es bisiesto o no
function esBisiesto(ano) {
	var bisiesto;
	var anoint = parseInt(ano);
	
	if(anoint%4==0){
		if(aonint%100==0){
			if(anoint%400==0) bisiesto=true;
			else bisiesto=false;		
		} else bisiesto=true;		
	} else bisiesto=false;

return bisiesto;
} 


/********* Funciones para AJAX *******/

function llamarasincrono(contenido, container){

	var peticion = new XMLHttpRequest();		// crea la vble peticion de tipo XMLHttpRequest(): para navegadores modernos. Para explorer 5 y 6 pondriamos -> var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
	
	peticion.onreadystatechange=function(){		// Se dispara cuando se produce un canvio de estado.
		cargar_pagina(peticion, container);	// cargamos la función k carga las paginas y cada vez k se carge cambiara de estado hasta k el readyState == 4.
	}

	peticion.open("GET", contenido, true);		// abre una petición con el método "GET" en la URL "contenido" y ponemos true para indicar
								// que el script continua la ejecucion despues de la llamada al metodo send() sin esperar a la respuesta.


	peticion.send(null);					// enviamos la peticion.
}

function cargar_pagina(peticion, container){
	if (peticion.readyState == 4){								// Devuelve el estado de la conexión (tiene 5 estados: 0,1,2,3,4). El estado 4 significa conexión acabada.
		document.getElementById(container).innerHTML=peticion.responseText;		// 'innerHTML': retorna el texto de un link.   'responseText': devuelve la respuesta como texto.
	}
}

/*function llamarasincrono(url, id_contenedor)
{
    var pagina_requerida = false;
    if (window.XMLHttpRequest)
    {
        // Si es Mozilla, Safari etc
        pagina_requerida = new XMLHttpRequest ();
    } else if (window.ActiveXObject)
    {
        // pero si es IE
        try 
        {
            pagina_requerida = new ActiveXObject ("Msxml2.XMLHTTP");
        }
        catch (e)
        {
            // en caso que sea una versión antigua
            try
            {
                pagina_requerida = new ActiveXObject ("Microsoft.XMLHTTP");
            }
            catch (e)
            {
            }
        }
    } 
    else
    return false;
    pagina_requerida.onreadystatechange = function ()
    {
        // función de respuesta
        cargarpagina (pagina_requerida, id_contenedor);
    }
    pagina_requerida.open ('GET', url, true); // asignamos los métodos open y send
    pagina_requerida.send (null);
}
// todo es correcto y ha llegado el momento de poner la información requerida
// en su sitio en la pagina xhtml
function cargarpagina (pagina_requerida, id_contenedor)
{
    if (pagina_requerida.readyState == 4 && (pagina_requerida.status == 200 || window.location.href.indexOf ("http") == - 1))
    document.getElementById (id_contenedor).innerHTML = pagina_requerida.responseText;
}
*/
