// Funció que permet veure si s'està executant bé el Javascript. Mostra un alert.
// v1.0 - 10/12/2008 - Àlex Arañó
var ajax_actiu = 0;

/*** AJAX_NOU.JS ***/
function creaAjax(){
         var objetoAjax=false;
         try {
          /*Para navegadores distintos a internet explorer*/
          objetoAjax = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
          try {
                   /*Para explorer*/
                   objetoAjax = new ActiveXObject("Microsoft.XMLHTTP");
                   }
                   catch (E) {
                   objetoAjax = false;
          }
         }

         if (!objetoAjax && typeof XMLHttpRequest!='undefined') {
          objetoAjax = new XMLHttpRequest();
         }
         return objetoAjax;
}
     
function FAjax (url,capa,valores,metodo)
{
	  var ajax=creaAjax();
	  var capaContenedora = document.getElementById(capa);

	/*Creamos y ejecutamos la instancia si el metodo elegido es POST*/
	if(metodo.toUpperCase()=='POST'){
			 ajax.open ('POST', url, true);
			 ajax.onreadystatechange = function() {
			 if (ajax.readyState==1) {
				capaContenedora.innerHTML = '<div style="margin-left: 40%; margin-top: 30px;"><img src="img/ajax-loader.gif" /></div>';
				ajax_actiu=1;
			 }
			 else if (ajax.readyState==4){
					   if(ajax.status==200)
					   {
							document.getElementById(capa).innerHTML=ajax.responseText;
							ajax_actiu = 0;
					   }
					   else if(ajax.status==404)
							   {
	
								capaContenedora.innerHTML = "La direccion no existe";
								ajax_actiu = 0;
							   }
							   else
							   {
								capaContenedora.innerHTML = "Error: ".ajax.status;
								ajax_actiu = 0;
							  }
					  }
					 // ajax_actiu = 0;
			 }
			 ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
			 ajax.send(valores);
			 return;
	}
	/*Creamos y ejecutamos la instancia si el metodo elegido es GET*/
	if (metodo.toUpperCase()=='GET'){
	
			 ajax.open ('GET', url, true);
			 ajax.onreadystatechange = function() {
			 if (ajax.readyState==1) {
				capaContenedora.innerHTML = '<div style="margin-left: 40%; margin-top: 30px;"><img src="img/ajax-loader.gif" /></div>';
			 }
			 else if (ajax.readyState==4){
					   if(ajax.status==200){
							document.getElementById(capa).innerHTML=ajax.responseText;
					   }
					   else if(ajax.status==404)
												 {
	
								capaContenedora.innerHTML = "La direccion no existe";
												 }
												 else
												 {
								capaContenedora.innerHTML = "Error: ".ajax.status;
												 }
										}
					  }
			 ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
			 ajax.send(null);
			 return;
	}
} 

// funcio ajax pel cercador de puntuacions
function FAjax_cerca (url,capa,valores,metodo)
{
	  var ajax=creaAjax();
	  var capaContenedora = document.getElementById(capa);

	/*Creamos y ejecutamos la instancia si el metodo elegido es POST*/
	if(metodo.toUpperCase()=='POST'){
			 ajax.open ('POST', url, true);
			 ajax.onreadystatechange = function() {
			 if (ajax.readyState==1) {
				// capaContenedora.innerHTML="Cargando.......";
			 }
			 else if (ajax.readyState==4){
					   if(ajax.status==200)
					   {
							document.getElementById(capa).innerHTML=ajax.responseText;
							$("#slider4").easySlider({
								prevText: '<img src="img/flecha_izq_on.png" alt="&laquo;" />',
								nextText: '<img src="img/flecha_der_on.png" alt="&raquo;" />',		
								firstShow: false,
								lastShow: false,
								vertical: false,
								id: 4,			
								continuous: false 		
							});
							if(document.getElementById('primera_partida')){
								mostra_puntuacio(document.getElementById('primera_partida').value);
							}else{
								document.getElementById('capa_puntuacion').innerHTML = '<div class="paginacion"> </div>';
							}
					   }
					   else if(ajax.status==404)
							   {

	
								capaContenedora.innerHTML = "La direccion no existe";
							   }
							   else
							   {
								capaContenedora.innerHTML = "Error: ".ajax.status;
							  }
					  }
			 }
			 ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
			 ajax.send(valores);
			 return;
	}
}

// funcio ajax per l'edicio de la caixa "altres dades" de la pagina d'usuari
function FAjax_altres (url,capa,valores,metodo)
{
	  var ajax=creaAjax();
	  var capaContenedora = document.getElementById(capa);

	/*Creamos y ejecutamos la instancia si el metodo elegido es POST*/
	if(metodo.toUpperCase()=='POST'){
			 ajax.open ('POST', url, true);
			 ajax.onreadystatechange = function() {
			 if (ajax.readyState==1) {
				capaContenedora.innerHTML = '<div style="margin-left: 40%; margin-top: 10px; min-height:'+(capaContenedora.offsetHeight - 10)+'px"><img src="img/ajax-loader.gif" /></div>';
			 }
			 else if (ajax.readyState==4){
					   if(ajax.status==200)
					   {
							document.getElementById(capa).innerHTML=ajax.responseText;
							tb_init('a.thickbox_ajax');
					   }
					   else if(ajax.status==404)
							   {
	
								capaContenedora.innerHTML = "La direccion no existe";
							   }
							   else
							   {
								capaContenedora.innerHTML = "Error: ".ajax.status;
							  }
					  }
			 }
			 ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
			 ajax.send(valores);
			 return;
	}
}

// funcio ajax que no fa cap accio al rebre resposta
function FAjax_clics (url,valores)
{
	 var ajax=creaAjax();

	 ajax.open ('POST', url, true);
	 
	 ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	 ajax.send(valores);
	 return;
}

// funcio ajax per la crida ajax de les promocions
function FAjax_promocions (url,capa,valores,metodo)
{
	  var ajax=creaAjax();
	  var capaContenedora = document.getElementById(capa);

	/*Creamos y ejecutamos la instancia si el metodo elegido es POST*/
	if(metodo.toUpperCase()=='POST'){
			 ajax.open ('POST', url, true);
			 ajax.onreadystatechange = function() {
			 if (ajax.readyState==1) {
				capaContenedora.innerHTML = '<div style="margin-left: 30%; margin-top: -2px;"><img src="img/ajax-loader-little.gif" /></div>';
			 }
			 else if (ajax.readyState==4){
					   if(ajax.status==200)
					   {
							document.getElementById(capa).innerHTML=ajax.responseText;
					   }
					   else if(ajax.status==404)
							   {
	
								capaContenedora.innerHTML = "La direccion no existe";
							   }
							   else
							   {
								capaContenedora.innerHTML = "Error: ".ajax.status;
							  }
					  }
			 }
			 ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
			 ajax.send(valores);
			 return;
	}
}

// funcio ajax per la crida ajax de valors a inserir com a value d'un input
function FAjax_input (url,input,valores,metodo)
{
	  var ajax=creaAjax();

	/*Creamos y ejecutamos la instancia si el metodo elegido es POST*/
	if(metodo.toUpperCase()=='POST'){
		 ajax.open ('POST', url, true);
		 ajax.onreadystatechange = function() {
			 if (ajax.readyState==1) {
				
			 }
			 else if (ajax.readyState==4){
				   if(ajax.status==200)
				   {
						document.getElementById(input).value=ajax.responseText;
				   }		   
			 }
		 }
		 ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		 ajax.send(valores);
		 return;
	}
}

// funcio ajax per la crida ajax de recarrega d'una inscripcio al gestor
function FAjax_inscripcio (url,capa,valores,metodo)
{
	  var ajax=creaAjax();

	/*Creamos y ejecutamos la instancia si el metodo elegido es POST*/
	if(metodo.toUpperCase()=='POST'){
		 ajax.open ('POST', url, true);
		 ajax.onreadystatechange = function() {
			 if (ajax.readyState==1) {
				
			 }
			 else if (ajax.readyState==4){
				   if(ajax.status==200)
				   {
						document.getElementById(capa).innerHTML=ajax.responseText;
				   }		   
			 }
		 }
		 ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		 ajax.send(valores);
		 return;
	}
}

// funcio ajax per la crida ajax des d'un lightbox
function FAjax_lightbox(url,valores,metodo)
{
	  var ajax=creaAjax();
	 
	/*Creamos y ejecutamos la instancia si el metodo elegido es POST*/
	if(metodo.toUpperCase()=='POST'){
		 ajax.open ('POST', url, true);
		 ajax.onreadystatechange = function() {
			 if (ajax.readyState==1) {
				
			 }
			 else if (ajax.readyState==4){
			   if(ajax.status==200)
			   {
					if(ajax.responseText == "1"){
						alert(alert_mail_torneig_1);
					}else if(ajax.responseText == "2"){
						alert(alert_mail_torneig_2);
					}else if(ajax.responseText == "3"){
						alert(alert_mail_torneig_3);
					}else if(ajax.responseText == "4"){
						alert(alert_mail_torneig_4);
					}else if(ajax.responseText == "OK"){
						alert(alert_mail_torneig_ok);
						self.parent.tb_remove();
					}else if(ajax.responseText == "KO1"){
						alert(alert_destacado_ko);
						self.parent.tb_remove();
					}else if(ajax.responseText == "Destacado"){
						alert(alert_destacado_ok);
						self.parent.tb_remove();
						// recarreguem la pagina per veure que el torneig s'ha destacat (no funciona)
						/*
						self.parent.reload();
						self.parent.alert(1);
						self.parent.history.go(0);
						*/
					}
			   }  
			 }
		 }
		 ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		 ajax.send(valores);
		 return;
	}
}
/*** FI AJAX_NOU.JS ***/


/*** CAMP.JS ***/
function afegir_camp(){
	var crida="bd_camp_favorito.php";
	if(document.getElementById('camp_preferit')){ 
		crida+="?id_camp="+document.getElementById('camp_preferit').value;
		crida+="&accio=1";
		cridaAJAX_preferits(crida,1);
	}
}

function treure_camp(){
	var crida="bd_camp_favorito.php";
	if(document.getElementById('camp_preferit')){ 
		crida+="?id_camp="+document.getElementById('camp_preferit').value;
		crida+="&accio=2";
		cridaAJAX_preferits(crida,2);
	}
}

// funcio generica d'AJAX
function cridaAJAX_preferits(url,accio){
	var httpRequest;
			
		var params="";

		try{
			params=url.split('?')[1];
			url=url.split('?')[0];
		}catch(e){}
		
        if (window.XMLHttpRequest) { // Mozilla, Safari, ...
            httpRequest = new XMLHttpRequest();
            if (httpRequest.overrideMimeType) {
                httpRequest.overrideMimeType('text/xml');
            }
        } else if (window.ActiveXObject) { // IE
            try {
                httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
            }
        }

        if (!httpRequest) {
            alert(error_ajax);
            return false;
        }
        httpRequest.onreadystatechange = function() { 
			//posicionaCapaLoading();
			//mostraCapaLoading();
			mostraResultat_preferits(httpRequest,accio); 
		};
        httpRequest.open('GET', url+"?"+params, true);
        httpRequest.send(null);
}


function mostraResultat_preferits(httpRequest,accio) {
	//document.location.href="#top";
	if(httpRequest.readyState < 4){//loading
		//	document.getElementById("load").innerHTML="<img src=\"imatges/cargando.gif\" id=\"cargando\" name=\"cargando\" width=\"25\"/>";
		//setTimeout(doNext,15000);
	}
    if (httpRequest.readyState == 4) {//la resposta un cop s'ha carregat
		//setTimeout(amagaCapaLoading,1000); 
        if (httpRequest.status == 200) {
            // Mostrem la taula resultant
			var resposta = httpRequest.responseText;   
			if(resposta == "OK"){
				if(accio == 1){
					document.getElementById('submenu2').style.display='inline';
					document.getElementById('submenu1').style.display='none';
				}else if(accio == 2){
					document.getElementById('submenu2').style.display='none';
					document.getElementById('submenu1').style.display='inline';
				}
			}else if(resposta == "KO_1"){
				if(accio == 1){
					alert(campo_favorito);
				}
			}else if(resposta == "KO_2"){
				if(accio == 1){
					alert(error_bbdd);
				}
			}
			
        } else {
            alert(error_peticion);
        }
    }

}
/*** FI CAMP.JS ***/


/*** CERCADOR.JS ***/
// recarrega del listbox de provincies segons la comunitat escollida
function carrega_provincies(id_comunitat){
	//alert(id_comunitat);
	var crida="ajax-cercador-provincies.php?target=select_provincia";
	if(id_comunitat != null){ 
		crida+="&comunitat="+id_comunitat;
		cridaAJAX_cerca(crida);
	}
}

// Cercador de camps
function cerca_camps(form,pagina){
	var validat = 1;
	var crida="ajax-cercador-camps.php?target=taula_resultats";
	if(pagina != null) crida+="&pagina="+pagina;
	if(typeof form != "undefined"){ 
		switch(form.name){
			case 'cerca1':
				crida+="&cercador=1";
				nom = form.nom_camp.value;
				if(nom.length > 0) crida+="&nom="+nom;
				
				for (i=0;i<form.tipus.length;i++){
					if (form.tipus[i].checked)
					  break;
				}
				crida+="&tipus="+form.tipus[i].value;
				
				for (i=0;i<form.forats.length;i++){
					if (form.forats[i].checked)
					  break;
				}
				crida+="&forats="+form.forats[i].value;
				
				if(form.select_provincia){
					provincia = form.select_provincia.value;
					if(provincia != 0) crida+="&provincia="+provincia;
				}
				cridaAJAX_cerca2(crida);
			break;
			
			case 'cerca2':
				crida+="&cercador=2";
				
				minuts = form.minuts.value;
				if(minuts.length > 0) crida+="&minuts="+minuts;
				else validat = 0;
				
				poblacio = form.poblacio.value;
				if(poblacio.length > 0) crida+="&poblacio="+poblacio;
				else validat = 0;
				
				for (i=0;i<form.tipus_camp.length;i++){
					if (form.tipus_camp[i].checked)
					  break;
				}
				crida+="&tipus="+form.tipus_camp[i].value;
				
				if(validat == 1) cridaAJAX_cerca2(crida);
				else alert(minutos_poblacion_obligatorios);
			break;
			
			case 'cerca3':
				
				minuts = form.minuts.value;
				if(minuts.length > 0) crida+="&minuts="+minuts;
				else validat = 0;
				
				poblacio = form.poblacio.value;
				if(poblacio.length > 0) crida+="&poblacio="+poblacio;
				else validat = 0;
				
				if(validat == 1){ 
					// redirigir al cercador.php passant-li les variables
					document.cerca3.action = "cercador.php";
					document.cerca3.submit();
				}else alert(minutos_poblacion_obligatorios);
			break;
			
		}
	}
	//alert(crida);
}

// funcio generica d'AJAX
function cridaAJAX_cerca(url){
	var httpRequest;
			
		var params="";

		try{
			params=url.split('?')[1];
			url=url.split('?')[0];
		}catch(e){}
		try{
			target=params.split('target=')[1].split('&')[0];
			
		}catch(e){
			target="";	
		}
        if (window.XMLHttpRequest) { // Mozilla, Safari, ...
            httpRequest = new XMLHttpRequest();
            if (httpRequest.overrideMimeType) {
                httpRequest.overrideMimeType('text/xml');
            }
        } else if (window.ActiveXObject) { // IE
            try {
                httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
            }
        }

        if (!httpRequest) {
            alert(error_ajax);
            return false;
        }
        httpRequest.onreadystatechange = function() { 
			//posicionaCapaLoading();
			//mostraCapaLoading();
			mostraResultat_cerca(httpRequest,target); 
		};
        httpRequest.open('GET', url+"?"+params, true);
        httpRequest.send(null);
}

function mostraResultat_cerca(httpRequest,target) {
	//document.location.href="#top";
	if(httpRequest.readyState < 4){//loading
		//	document.getElementById("load").innerHTML="<img src=\"imatges/cargando.gif\" id=\"cargando\" name=\"cargando\" width=\"25\"/>";
		//setTimeout(doNext,15000);
	}
    if (httpRequest.readyState == 4) {//la resposta un cop s'ha carregat
		//setTimeout(amagaCapaLoading,1000); 
        if (httpRequest.status == 200) {
            // Mostrem la taula resultant
			var resposta = httpRequest.responseText;   
			//alert(resposta);
			document.getElementById(target).innerHTML = resposta;
			
        } else {
            alert(error_peticion);
        }
    }

}


// funcio generica d'AJAX
function cridaAJAX_cerca2(url){
	var httpRequest;
			
		var params="";

		try{
			params=url.split('?')[1];
			url=url.split('?')[0];
		}catch(e){}
		try{
			target=params.split('target=')[1].split('&')[0];
			
		}catch(e){
			target="";	
		}
        if (window.XMLHttpRequest) { // Mozilla, Safari, ...
            httpRequest = new XMLHttpRequest();
            if (httpRequest.overrideMimeType) {
                httpRequest.overrideMimeType('text/xml');
            }
        } else if (window.ActiveXObject) { // IE
            try {
                httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
            }
        }

        if (!httpRequest) {
            alert(error_ajax);
            return false;
        }
        httpRequest.onreadystatechange = function() { 
			//posicionaCapaLoading();
			//mostraCapaLoading();
			mostraResultat_cerca2(httpRequest,target); 
		};
        httpRequest.open('GET', url+"?"+params, true);
        httpRequest.send(null);
}

// callback especial per la cerca amb googlemaps
function mostraResultat_cerca2(httpRequest,target) {
	//document.location.href="#top";
	if(httpRequest.readyState < 4){//loading
		document.getElementById(target).innerHTML = '<div style="margin-left: 40%; margin-top: 30px;"><img src="img/ajax-loader.gif" /></div>';
		//setTimeout(doNext,15000);
	}
    if (httpRequest.readyState == 4) {//la resposta un cop s'ha carregat
		//setTimeout(amagaCapaLoading,1000); 
        if (httpRequest.status == 200) {
            // Mostrem la taula resultant
			
            //resposta=httpRequest.responseXML;
			var resposta = eval('(' + httpRequest.responseText + ')');
			//alert(resposta.contingut);
			//alert(resposta.longitut+','+resposta.latitut+','+resposta.zoom);
			document.getElementById(target).innerHTML = resposta.contingut;
			// inicialitzem l'slider per la paginacio dels resultats de la cerca de camps (jQuery)	
				$("#slider7").easySlider({
					prevText: '<img src="img/flecha_izq_on.png" alt="&laquo;" />',
					nextText: '<img src="img/flecha_der_on.png" alt="&raquo;" />',		
					firstShow: false,
					lastShow: false,
					vertical: false,
					id: 7,			
					continuous: false 		
				});
				
			tb_init('a.thickbox_ajax');
			
			if((resposta.longitut == 41.55745) || (resposta.accio == 0)){
				ubica_mapa(40.163667,-3.14922, 5);
			}else{
				if(map == undefined) initialize();
				posa_markers(resposta.longitut,resposta.latitut,resposta.markers);
			}
			//ubica_mapa(resposta.longitut,resposta.latitut,resposta.zoom);
			/*
				var xmlDoc = document.implementation.createDocument("", "", null);
				xmlDoc.load(httpRequest.responseText);

				//var	id=xmlDoc.getElementsByTagName("id")[0].firstChild.data;
				var html=xmlDoc.getElementsByTagName("html");
				*/
				/*
				var xml = httpRequest.responseXML.documentElement;
				var itema = xml.getElementsByTagName('html')[0];
				alert(xml.firstChild);
				*/
				/*
				var comentaris=document.createElement('li');
				comentaris.innerHTML=html[0].firstChild.data;
				document.getElementById("persona_"+id).appendChild(comentaris);
	//			document.getElementById("persona_"+id).appendChild=html[0].firstChild.data;
				document.getElementById("veure_comentaris_"+id).style.visibility='hidden';
				*/
				//document.getElementById(target).innerHTML=xml.firstChild.data;
			
			
        } else {
            alert(error_peticion);
			document.getElementById(target).innerHTML = 'ERROR';
        }
    }

}

// Cercador de tornejos
function cerca_tornejos(form){
	var validat = 1;
	var crida="ajax-cercador-tornejos.php?target=taula_resultats";
	if(typeof form != "undefined"){ 
		switch(form.name){
			case 'cerca1':
				crida+="&cercador=1";
				nom = form.nom_camp.value;
				if(nom.length > 0) crida+="&nom="+nom;
				
				for (i=0;i<form.tipus.length;i++){
					if (form.tipus[i].checked)
					  break;
				}
				crida+="&tipus="+form.tipus[i].value;
				
				if(form.select_provincia){
					provincia = form.select_provincia.value;
					if(provincia != 0) crida+="&provincia="+provincia;
				}
				
				if(form.data_inici){
					data_inici = form.data_inici.value;
					if(data_inici != '') crida+="&data_inici="+data_inici;
				}
				
				if(form.data_fi){
					data_fi = form.data_fi.value;
					if(data_fi != '') crida+="&data_fi="+data_fi;
				}
				
				cridaAJAX_cerca2(crida);
			break;
			
			case 'cerca2':
				crida+="&cercador=2";
				
				minuts = form.minuts.value;
				if(minuts.length > 0) crida+="&minuts="+minuts;
				else validat = 0;
				
				poblacio = form.poblacio.value;
				if(poblacio.length > 0) crida+="&poblacio="+poblacio;
				else validat = 0;
				
				for (i=0;i<form.tipus_camp.length;i++){
					if (form.tipus_camp[i].checked)
					  break;
				}
				crida+="&tipus="+form.tipus_camp[i].value;
				
				if(validat == 1) cridaAJAX_cerca2(crida);
				else alert(minutos_poblacion_obligatorios);
			break;
			
		}
	}
	//alert(crida);
}

// reset del formulari de cerca de tornejos
function reset_form_cercador(){
	document.getElementById('cerca1').reset();
	document.getElementById('select_provincia').innerHTML = '<select name="select_provincia" ><option value="0">'+escoger_comunidad+'</option></select>';
	document.getElementById('data_inici').value = '';
}
/*** FI CERCADOR.JS ***/

/*** STAR.JS ***/
/* AJAX Star Rating : v1.0.3 : 2008/05/06 */
/* http://www.nofunc.com/AJAX_Star_Rating/ */

//function $(v,o) { return((typeof(o)=='object'?o:document).getElementById(v)); } /*aixo fa que no funcioni accordion*/
function $S(o) { return((typeof(o)=='object'?o:$(o)).style); }
function agent(v) { return(Math.max(navigator.userAgent.toLowerCase().indexOf(v),0)); }
function abPos(o) { var o=(typeof(o)=='object'?o:$(o)), z={X:0,Y:0}; while(o!=null) { z.X+=o.offsetLeft; z.Y+=o.offsetTop; o=o.offsetParent; }; return(z); }
function XY(e,v) { var o=agent('msie')?{'X':event.clientX+document.documentElement.scrollLeft,'Y':event.clientY+document.documentElement.scrollTop}:{'X':e.pageX,'Y':e.pageY}; return(v?o[v]:o); }


star={};

star.mouse=function(e,o) { if(star.stop || isNaN(star.stop)) { star.stop=0;

	document.onmousemove=function(e) { var n=star.num;	
		//var p=abPos(document.getElementById('star'+n)), x=XY(e), oX=x.X-p.X, oY=x.Y-p.Y; star.num=o.id.substr(4);
		var p=abPos(document.getElementById('star'+n)), x=XY(e), oX=x.X-p.X, oY=x.Y-p.Y; star.num=o.id.substr(4);

		if(oX<0 || oX>50 || oY<0 || oY>6) { star.stop=1; star.revert(); }
		
		else {
			if(document.getElementById('star'+n)){
				document.getElementById('star'+n).style.backgroundPosition = '0px -'+oX+'px';
				document.getElementById('porcentaje'+n).innerHTML= (oX*2)+'%';
			}
		}
	};
} };

star.update=function(e,o,id_camp) { var n=star.num, v=parseInt(document.getElementById('porcentaje'+n).innerHTML);

	//n=o.id.substr(4); document.getElementById('starCur'+n).title=v;
	n=o.id.substr(4); document.getElementById('star'+n).title=v;

	var url = 'ajax_valoracio_camp.php?camp='+id_camp+'&categoria='+n+'&valor='+v;
	//alert(url);
	puntuacionsAJAX(url);
};

// funcio generica d'AJAX
function puntuacionsAJAX(url){
	var httpRequest;
			
		var params="";

		try{
			params=url.split('?')[1];
			url=url.split('?')[0];
		}catch(e){}
		
        if (window.XMLHttpRequest) { // Mozilla, Safari, ...
            httpRequest = new XMLHttpRequest();
            if (httpRequest.overrideMimeType) {
                httpRequest.overrideMimeType('text/xml');
            }
        } else if (window.ActiveXObject) { // IE
            try {
                httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
            }
        }

        if (!httpRequest) {
            alert(error_ajax);
            return false;
        }
        httpRequest.onreadystatechange = function() { 
			alertResultat(httpRequest); 
		};
        httpRequest.open('GET', url+"?"+params, true);
        httpRequest.send(null);
}

function alertResultat(httpRequest) {
	//document.location.href="#top";
	if(httpRequest.readyState < 4){//loading
		
	}
    if (httpRequest.readyState == 4) {//la resposta un cop s'ha carregat
		
        if (httpRequest.status == 200) {
            // Mostrem la taula resultant
            resposta=httpRequest.responseText;
			//alert(resposta);
        } else {
            alert(error_peticion);
        }
    }

}

star.revert=function() { 

	var n=star.num, v=parseInt(document.getElementById('star'+n).title);
	
	document.getElementById('star'+n).style.backgroundPosition = '0px -'+v/2+'px';
	document.getElementById('porcentaje'+n).innerHTML= v+'%';
	
	document.onmousemove='';

};

star.num=0;
/*** FI STAR.JS ***/


function submitComentaCamp(form){
	if(document.getElementById('comentario').value.length>0){
		form.submit();
	}else{
		alert(comentario_obligatorio);
	}
}

function getElementsIdByClass(node,searchClass,tag) {
    var classElements = new Array();
    var els = node.getElementsByTagName(tag); // use "*" for all elements
    var elsLen = els.length;
    for (i = 0, j = 0; i < elsLen; i++) {
         if ( searchClass == els[i].className ) {
             classElements[j] = els[i].id;
             j++;
         }
    }
    return classElements;
}

function selecciona_fila( num_partida ){
	var id = getElementsIdByClass(document,'fila_sel','div');
	if((id != null) && (id != '')){
		document.getElementById(id).className  = 'fila';
	}
	document.getElementById('fila_'+num_partida).className  = 'fila_sel';
}

function mostra_puntuacio( num_partida ){
	if(ajax_actiu == 0){
		ajax_actiu = 1;
		selecciona_fila( num_partida );
		
		FAjax('ajax_puntuacio.php','capa_puntuacion','id_partida='+num_partida,'post');
	}
}

function ver_detalles_partida( num_partida ){
	if(ajax_actiu == 0){
		ajax_actiu = 1;
		FAjax('ajax-partida-detalles.php','capa_puntuacion','id_partida='+num_partida,'post');
	}
}

function ver_estadisticas_partida( num_partida ){
	if(ajax_actiu == 0){
		ajax_actiu = 1;
		FAjax('ajax-partida-estadisticas.php','capa_puntuacion','id_partida='+num_partida,'post');
	}
}

function editar_grup(id_grup){
	if((id_grup != null) && (id_grup > 0)){
		var nom_grup = document.getElementById('hidden_grup').value;
		FAjax('ajax_grup_edit.php','dades_grup','tasca=edita_grup&g='+id_grup+'&nom='+nom_grup,'post');
	}
}

function edita_handicaps(){
	FAjax('ajax_usuari.php','capa_handicaps','tasca=edita_handicaps','post'); 
}

function desa_handicaps(){
	//validació dels handicaps
	var hcp_golf = document.getElementById("hcp_golf").value.replace(",", ".");
	if(isNaN(hcp_golf) && hcp_golf.length > 0){
		alert(alert_handicap);
		return(false);
	}else{
		hcp_golf = Number(hcp_golf);
		hcp_golf = hcp_golf.toFixed(1);
		if(hcp_golf>99 || hcp_golf<-10){
			alert(handicap_incorrecto);
		}else{
			var hcp_pp =  document.getElementById("hcp_pp").value.replace(",", ".");
			if(isNaN(hcp_pp) && hcp_pp.length > 0){
				alert(alert_handicap);
				return(false);
			}else{
				hcp_pp = Number(hcp_pp);
				hcp_pp = hcp_pp.toFixed(1);
				if(hcp_pp>99 || hcp_pp<-10){
					alert(handicap_incorrecto);
				}else{
					FAjax('ajax_usuari.php','capa_handicaps','tasca=desa_handicaps&hcp_golf='+hcp_golf+'&hcp_pp='+hcp_pp,'post');
				}
			}
		}
	}
}

function edita_altres_dades(){
	FAjax_altres('ajax_usuari.php','altres_dades','tasca=edita_altres_dades','post'); 
}

function desa_altres_dades(){
	var input_genere = '';
	if(document.getElementById('input_genere_M').checked)
		input_genere = document.getElementById('input_genere_M').value;
	else if(document.getElementById('input_genere_F').checked)
		input_genere = document.getElementById('input_genere_F').value;
		
	//input_genereF = document.getElementById('input_genere_F').value;
	var input_movil = document.getElementById('input_movil').value;
	
	var handicap_pp = document.getElementById('handicap_pp').value;
	var handicap_golf = document.getElementById('handicap_golf').value;
	var llicencia_pp = document.getElementById('llicencia_pp').value;
	if(document.getElementById('llicencia_pp_in').value.length==0)
		llicencia_pp = '';
	var llicencia_golf = document.getElementById('llicencia_golf').value;
	if(document.getElementById('llicencia_golf_in').value.length==0)
		llicencia_golf = '';
	//var password_pp = document.getElementById('password_pp').value;
	//var password_golf = document.getElementById('password_golf').value;

	//FAjax('ajax_usuari.php','altres_dades','tasca=desa_altres_dades&input_genere='+input_genere+'&input_movil='+input_movil+'&handicap_pp='+handicap_pp+'&handicap_golf='+handicap_golf+'&llicencia_pp='+llicencia_pp+'&llicencia_golf='+llicencia_golf+'&pwd_pp='+password_pp+'&pwd_golf='+password_golf,'post');
	FAjax('ajax_usuari.php','altres_dades','tasca=desa_altres_dades&input_genere='+input_genere+'&input_movil='+input_movil+'&handicap_pp='+handicap_pp+'&handicap_golf='+handicap_golf+'&llicencia_pp='+llicencia_pp+'&llicencia_golf='+llicencia_golf,'post');
	
	// fem una pausa i comprovem si hem rebut un error en forma de camp hidden en la resposta AJAX
	//setTimeout("comprova_error_edit_altres_dades()", 2500);
	
}

function comprova_error_edit_altres_dades(){
	if(document.getElementById('error_edit')){
		if(document.getElementById('error_edit').value == '1'){
			alert(error_licencia_pp_asignada);
		}
		if(document.getElementById('error_edit').value == '2'){
			alert(error_licencia_golf_asignada);
		}
	}
}

function crea_nou_grup(){
	FAjax('ajax_usuari.php','capa_nou_grup','tasca=crea_nou_grup','post'); 
}

function cancela_nou_grup(){
	FAjax('ajax_usuari.php','capa_nou_grup','tasca=cancela_nou_grup','post'); 
}


function edita_dades_personals(){
	FAjax('ajax_usuari.php','dades_personals','tasca=edita_dades_personals','post'); 
}

function desa_dades_personals(){
	if( document.getElementById('input_nom').value.length == 0 ){
		alert(nombre_obligatorio);
	}else{
		if( document.getElementById('input_password').value.length == 0 ){
			alert(password_obligatorio);
		}else{
			var input_nom = document.getElementById('input_nom').value;
			var input_poblacio = document.getElementById('input_poblacio').value;
			var input_provincia = document.getElementById('input_provincia').value;
			var input_password = document.getElementById('input_password').value;
			var input_dia = document.getElementById('input_dia').value;
			var input_mes = document.getElementById('input_mes').value;
			var input_any = document.getElementById('input_any').value;
			
			FAjax('ajax_usuari.php','dades_personals','tasca=desa_dades_personals&input_nom='+input_nom+'&input_poblacio='+input_poblacio+'&input_provincia='+input_provincia+'&input_password='+input_password+'&input_dia='+input_dia+'&input_mes='+input_mes+'&input_any='+input_any,'post'); 
		}
	}
}

function edita_equipament(){
	
	FAjax('ajax_usuari.php','equipament','tasca=edita_equipament','post'); 
}

function desa_equipament(){
	var input_equipament = document.getElementById('input_equipament').value;
	input_equipament = ReplaceEnters(input_equipament, true);
	FAjax('ajax_usuari.php','equipament','tasca=desa_equipament&input_equipament='+input_equipament,'post');
}

function contadorTextArea(){
	
	if(document.getElementById('comentario').value.length>140){
		document.getElementById('comentario').value=document.getElementById('comentario').value.substring(0,140);
	}else{
		document.getElementById('contador').innerHTML = document.getElementById('comentario').value.length+'/140'; 
	}
}

function comprovarPuntuacions(){
	var crida = "excel/ajax_comprovaPuntuacions.php?data_inici="+document.getElementById('f_date_c_data_inici').value+"&data_fi="+document.getElementById('f_date_c_data_fi').value+"&id_camp="+document.getElementById('id_camp').value+"&id2_jugador="+document.getElementById('id2_jugador').value+"&nickname_jugador="+document.getElementById('nickname_jugador').value;
	cridaAJAX_EXCEL(crida);
}

function reemplazar(cadena,quitar,poner){
// USO: En el parámetro cadena, sustituye
// toda ocurrencia del parámetro quitar por
// el parámetro poner. Devuelve la cadena
// resultante de la sustitución.

	if (cadena == "" || quitar == "") return cadena;
	var expReg = eval("/" + quitar + "/g");
	return cadena.replace(expReg,poner);
}


/***** Funcion para cambiar de pestaña activa *****/
function canvia_pestana(num){
	document.getElementById('pestana_activa').value = num;
	//alert(document.getElementById('pestana_activa').value);
	document.form_pestana.submit();
}

/***** Funcion para cambiar de idioma activo *****/
function canvia_idioma(num){
	document.getElementById('idioma_actiu').value = num;
	//alert(document.getElementById('pestana_activa').value);
	document.form_idioma.submit();
}

/***** Funcions per redireccionar a URLs amigables amb pas de parametre extra *****/
function puntuacion_jugador(url,valor){
	document.form_redireccions.action = url;
	document.getElementById('partida').value = valor;
	document.form_redireccions.submit();
}
function puntuacion_grupo(url,valor){
	document.form_redireccions.action = url;
	document.getElementById('partida').value = valor;
	document.form_redireccions.submit();
}

//introducir_puntuacions autocompletar
var myAjax = ajax();
function ajax() {
   var ajax = null;
   if (window.XMLHttpRequest) {
      try {
         ajax = new XMLHttpRequest();
      }
      catch(e) {}
   }
   else if (window.ActiveXObject) {
      try {
         ajax = new ActiveXObject("Msxm12.XMLHTTP");
      }
      catch (e){
         try{
            ajax = new ActiveXObject("Microsoft.XMLHTTP");
         }
         catch (e) {}
      }
   }
   return ajax;
}
function request(str) {
   //Don't forget to modify the path according to your theme
   myAjax.open("POST", "ajax_puntuacions.php");
   myAjax.onreadystatechange = result;
   myAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
   myAjax.send("search="+str);
}
function result() {
   if (myAjax.readyState == 4) {
      var liste = myAjax.responseText;
      var cible = document.getElementById('tag_update').innerHTML = liste;
	  if( (liste != '') && (liste != '<ul></ul>') ){
      	document.getElementById('tag_update').style.display = "block";
	  }else
	  	document.getElementById('tag_update').style.display = "none";
   }
}

function request2(str) {
   //Don't forget to modify the path according to your theme
   //eliminem el contingut de la capa d'autocompletar
   //alert(str);
   document.getElementById('tag_update').innerHTML = "";
   document.getElementById('tag_update').style.display = "none";
   myAjax.open("POST", "ajax_busqueda_form.php");
   myAjax.onreadystatechange = result2;
   myAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
   myAjax.send("search="+str);
}

function result2() {
   if (myAjax.readyState == 4) {
      var liste = myAjax.responseText;
	  if(liste != "0")
	  	camp_busq(liste);
      else{
	  	document.getElementById('tag_update').innerHTML = "";
		document.getElementById('tag_update').style.display = "none";
	  }
   }
}


/*
function selected(choice){
   var cible = document.getElementById('s');
      var posc = 0;
      for (var i=cible.value.length-1; i>=0; i--)   {
         var caracter = cible.value[i];
         if (caracter==" "){
            posc = i+1;
            break;
         }
      }
   cible.value = cible.value.substring(0,posc)+""+choice;
   cible.focus();
   document.getElementById('tag_update').style.display = "none";
}
*/
function selected(choice){
   var cible = document.getElementById('s');
   choice = reemplazar(choice,"&amp;","&")
   cible.value = choice;
   cible.focus();
   document.getElementById('tag_update').style.display = "none";
}

function mostra_tagupdate(){
	if(document.getElementById('tag_update').innerHTML.length > 2)
		document.getElementById('tag_update').style.display = "block";
}

function amaga_tagupdate(){
	document.getElementById('tag_update').style.display = "none";
}
//fin introducir_puntuacions autocompletar



//muestra el favorito seleccionado en el campo de busqueda
/*function favorito (id2) {
		//desmarcamos el resto
		for (i=0;i<document.favoritoform.elements.length;i++)
		{
			if(document.favoritoform.elements[i].type == "checkbox")
			{
				if(document.favoritoform.elements[i].id != 'campo'+id2)
				{
				document.favoritoform.elements[i].checked=false;
				}
			}
		} 
		//marcamos en el campo de búsqueda el seleccionado
		if(document.getElementById('campo'+id2).checked==true)
		{	
			document.getElementById('s').value=id2;
		}
	
	
}*/

// funcio generica d'AJAX
function cridaAJAX(url){
	var httpRequest;
			
		var params="";

		try{
			params=url.split('?')[1];
			url=url.split('?')[0];
		}catch(e){}
		try{
			target=params.split('target=')[1].split('&')[0];
			
		}catch(e){
			target="";	
		}
        if (window.XMLHttpRequest) { // Mozilla, Safari, ...
            httpRequest = new XMLHttpRequest();
            if (httpRequest.overrideMimeType) {
                httpRequest.overrideMimeType('text/xml');
            }
        } else if (window.ActiveXObject) { // IE
            try {
                httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
            }
        }

        if (!httpRequest) {
            alert(error_ajax);
            return false;
        }
        httpRequest.onreadystatechange = function() { 
			//posicionaCapaLoading();
			//mostraCapaLoading();
			mostraResultat(httpRequest); 
		};
        httpRequest.open('GET', url+"?"+params, true);
        httpRequest.send(null);
}


function mostraResultat(httpRequest) {
	//document.location.href="#top";
	if(httpRequest.readyState < 4){//loading
		//alert("estat igual a 1");
		//	document.getElementById("load").innerHTML="<img src=\"imatges/cargando.gif\" id=\"cargando\" name=\"cargando\" width=\"25\"/>";
		
		//setTimeout(doNext,15000);
	}
    if (httpRequest.readyState == 4) {//la resposta un cop s'ha carregat
		//setTimeout(amagaCapaLoading,1000); 
        if (httpRequest.status == 200) {
            // Mostrem la taula resultant
            resposta=httpRequest.responseText;
			document.getElementById(target).innerHTML=resposta;
			// si comprovem que el mail ja existeix, l'esborrem del form perque n'hagi de posar un altre
			if(resposta=='<div class="input_jugador" style="color:red; width:210px;">Ya existe este email</div> <br />'){
				document.getElementById('login').value='';
			}else if(resposta=='<div class="input_jugador" style="color:red; width:210px;">Ya existe este nickname</div> <br />'){
				document.getElementById('nick').value='';
			}else if(resposta=='Ya existe un grupo con este nombre'){
				document.getElementById('nom_grup').value='';
			}
        } else {
            alert(error_peticion);
        }
    }

}

//busqueda de datos segun el tee
function actualitza_tees(id_tee)
{
	var id_camp = document.getElementById('camp_escollit').value;
	var crida = "ajax_puntuacions_taula.php?s="+id_camp+"&tee="+id_tee+"&target=taula_puntuacions";
	cridaAJAX_puntuacions(crida);
	select_all();
	if(document.getElementById('putts')){
		document.getElementById('putts').checked = false;
	}
	if(document.getElementById('fairways')){
		document.getElementById('fairways').checked = false;
	}
}

//busqueda de datos segun el tee en editar_puntuacion.php
function actualitza_tees_edit(id_tee,s1,s2,s3,s4,s5,s6,s7,s8,s9,s10,s11,s12,s13,s14,s15,s16,s17,s18)
{
	var id_camp = document.getElementById('camp_escollit').value;
	var putts = 0;
	var fairways = 0;
	if(document.getElementById('putts')){
		if(document.getElementById('putts').checked)
			putts = 1;
	}
	var crida = "ajax_puntuacions_taula_edit.php?s="+id_camp+"&tee="+id_tee+"&target=taula_puntuacions&s1="+s1+"&s2="+s2+"&s3="+s3+"&s4="+s4+"&s5="+s5+"&s6="+s6+"&s7="+s7+"&s8="+s8+"&s9="+s9+"&s10="+s10+"&s11="+s11+"&s12="+s12+"&s13="+s13+"&s14="+s14+"&s15="+s15+"&s16="+s16+"&s17="+s17+"&s18="+s18+"&putts="+putts;
	if(putts == 1){
		for(p=1;p<=18;p++){
			crida += "&p"+p+"="+document.getElementById('putt'+p).value;
		}
		for(p=1;p<=18;p++){
			crida += "&gir"+p+"="+document.getElementById('gir'+p).value;
		}
	}
	if(document.getElementById('fairways')){
		if(document.getElementById('fairways').checked)
			fairways = 1;
		crida += "&fairways="+fairways;
		if(fairways == 1){
			for(f=1;f<=18;f++){
				if( document.getElementById('fairway'+f)){
					if(document.getElementById('fairway'+f).checked)
						crida += "&f"+f+"=1";
					else 
						crida += "&f"+f+"=0";
				}
			}
		}
	}
	cridaAJAX_puntuacions(crida);
	select_all();
}

//busqueda de datos segun el tee
function actualitza_tees_grup(id_tee)
{
	var id_camp = document.getElementById('camp_escollit').value;
	if( (document.getElementById('tipus_puntuacio_actual')) && (document.getElementById('tipus_puntuacio_actual').value == 'grup') ){
		if( (document.getElementById('grupo')) && (document.getElementById('num_jugadors')) && (document.getElementById('grupo').value !=0) && (document.getElementById('num_jugadors').value != 0) ){
			crida = "ajax_puntuacions_taula.php?s="+id_camp+"&tee="+id_tee+"&g="+document.getElementById('grupo').value+"&num="+document.getElementById('num_jugadors').value+"&target=taula_puntuacions";
		}else{
			alert(seleccionar_grupo_jugadores);	
		}
	}else{
		var crida = "ajax_puntuacions_taula.php?s="+id_camp+"&tee="+id_tee+"&target=taula_puntuacions";
	}
	cridaAJAX_puntuacions(crida);
	if(document.getElementById('putts')){
		document.getElementById('putts').checked = false;
	}
	if(document.getElementById('fairways')){
		document.getElementById('fairways').checked = false;
	}
}

//busqueda de datos segun el camp
function camp_busq(id)
{
	amaga_tagupdate();
	if( (id != '') && (id != undefined) && (id != null)){
		var crida = '';
		if( (document.getElementById('tipus_puntuacio_actual')) && (document.getElementById('tipus_puntuacio_actual').value == 'grup') ){
			if( (document.getElementById('grupo')) && (document.getElementById('num_jugadors')) && (document.getElementById('grupo').value !=0) && (document.getElementById('num_jugadors').value != 0) ){
				crida = "ajax_puntuacions_grup.php?s="+id+"&g="+document.getElementById('grupo').value+"&num="+document.getElementById('num_jugadors').value;
			}else{
				alert(seleccionar_grupo_jugadores);	
			}
		}else{	
			crida = "ajax_puntuacions_tees.php?s="+id;
		}
		if(crida != ''){
			cridaAJAX2(crida);
		}
	}
}


/*
//busqueda de is segun el nombre delcamp
function camp_id()
{
	var nom = document.getElementById('s').value;
	window.location= "ajax_buscar_id.php?nom="+nom;
	
}
*/

// funcio d'AJAX especifica
function cridaAJAX2(url){
	var httpRequest;
			
		var params="";

		try{
			params=url.split('?')[1];
			url=url.split('?')[0];
		}catch(e){}
		try{
			//target=params.split('target=')[1].split('&')[0];
			target=params.split('s=')[1];
			//target="";	
 		}catch(e){
			target="";	
		}
        if (window.XMLHttpRequest) { // Mozilla, Safari, ...
            httpRequest = new XMLHttpRequest();
            if (httpRequest.overrideMimeType) {
                httpRequest.overrideMimeType('text/xml');
            }
        } else if (window.ActiveXObject) { // IE
            try {
                httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
            }
        }

        if (!httpRequest) {
            alert(error_ajax);
            return false;
        }
        httpRequest.onreadystatechange = function() { 
			//posicionaCapaLoading();
			//mostraCapaLoading();
			camp_busq_callback(httpRequest,target); 
		};
        httpRequest.open('GET', url+"?"+params, true);
        httpRequest.send(null);
}



//muestra los resultados
function camp_busq_callback(httpRequest,target){
					
		 if (httpRequest.readyState == 4) {//la resposta un cop s'ha carregat
			//setTimeout(amagaCapaLoading,1000); 
			if (httpRequest.status == 200) {
				resposta=httpRequest.responseText;
				document.getElementById('result_busqueda').innerHTML=resposta;
				document.getElementById('result_busqueda').style.display = "block";
			  
				if(document.getElementById('f_date_c_fecha_puntuacions')){
					Calendar.setup({
								inputField     :    "f_date_c_fecha_puntuacions",     // id of the input field
								ifFormat       :    "%d/%m/%Y ",      // format of the input field
								button         :    "f_trigger_c_fecha_puntuacions",  // trigger for the calendar (button ID)
								align          :    "Tl",           // alignment (defaults to 'Bl')
								singleClick    :    true
							});
				}
				cridaAJAX_puntuacions("ajax_puntuacions_taula.php?s="+target+"&target=taula_puntuacions");
				
			} else {
				alert(error_peticion);
			}
		}


}



//valida los numeros de las tablas de introducir_puntuacions
function validarNumero(numero)
{
	//si ha insertado un valor
	if (numero.length > 0) {
		//que sea numero
		if(!/^[0-9]+$/.test(numero))
		{
		  alert("El valor " + numero + " no es un número");
		}
		  
		 //que sea de longitud 2
		 if (numero.length > 2) {
			alert(maximo_2_digitos);
			return (false);
		 }
		 
		 //que sea positivo
		 if (numero <= 0) {
			alert(numero_positivo_obligatorio);
			return (false);
		 }
	}
}

//valida los numeros de las tablas de introducir_puntuacions al gestor (permetem puntuacions parcials)
function validarNumero_gestor(numero)
{
	//si ha insertado un valor
	if (numero.length > 0) {
		//que sea numero
		if(!/^[0-9]+$/.test(numero))
		{
		  alert("El valor " + numero + " no es un número");
		}
		  
		 //que sea de longitud 2
		 if (numero.length > 2) {
			alert(maximo_2_digitos);
			return (false);
		 }
		 
		 //que sea positivo (excepte per STABLEFORD on 0=>bola aixecada)
		 if(document.getElementById('modalidad') && (document.getElementById('modalidad').value == 2 || document.getElementById('modalidad').value == 3 || document.getElementById('modalidad').value == 4 || document.getElementById('modalidad').value == 5 || document.getElementById('modalidad').value == 8) ){
			 if (numero < 0) {
				alert(numero_positivo_obligatorio);
				return (false);
			 }
		 }else{
			 if (numero <= 0) {
				alert(numero_positivo_obligatorio);
				return (false);
			 }
		 }
	}
}

//valida los numeros de las tablas de introducir_puntuacions
function actualitza_casella_cop(id,valor,par)
{
	if( (valor != '') && (valor > 0) ){
		var resta = valor - par;
		switch(resta){
			case -2: document.getElementById(id).style.background = "#C0DCB2";
			break;
			case -1: document.getElementById(id).style.background = "#E0EED9";
			break;
			case 0: document.getElementById(id).style.background = "#FFFFFF";
			break;
			case 1: document.getElementById(id).style.background = "#FFE6D9";
			break;
			case 2: document.getElementById(id).style.background = "#FFCCB2";
			break;
			case 3: document.getElementById(id).style.background = "#FFB28C";
			break;
			default: if(resta < -2){
						document.getElementById(id).style.background = "#C0DCB2";
					}else if(resta > 3){
						document.getElementById(id).style.background = "#FFB28C";
					}
			break;
		}
	}else document.getElementById(id).style.background = "#FFFFFF";
}

//valida los numeros de las tablas de introducir_puntuacions al gestor (permetem puntuacions parcials)
function actualitza_casella_cop_gestor(id,valor,par)
{
	// per PROAM mostrem sempre fons blanc (canviar a modalitat == 9 )
	if(document.getElementById('modalidad').value == 8){
		document.getElementById(id).style.background = "#FFFFFF";
	}else{
		if( (valor != '') && (valor > 0) ){
			var resta = valor - par;
			switch(resta){
				case -2: document.getElementById(id).style.background = "#C0DCB2";
				break;
				case -1: document.getElementById(id).style.background = "#E0EED9";
				break;
				case 0: document.getElementById(id).style.background = "#FFFFFF";
				break;
				case 1: document.getElementById(id).style.background = "#FFE6D9";
				break;
				case 2: document.getElementById(id).style.background = "#FFCCB2";
				break;
				case 3: document.getElementById(id).style.background = "#FFB28C";
				break;
				default: if(resta < -2){
							document.getElementById(id).style.background = "#C0DCB2";
						}else if(resta > 3){
							document.getElementById(id).style.background = "#FFB28C";
						}
				break;
			}
		}else{ 
			// per STABLEFORD contem el 0 com a bola aixecada --> marquem el forat com a triple bogey o superior
			if(valor == '0' && document.getElementById('modalidad') && (document.getElementById('modalidad').value == 2 || document.getElementById('modalidad').value == 3 || document.getElementById('modalidad').value == 4 || document.getElementById('modalidad').value == 5) ){
				document.getElementById(id).style.background = "#FFB28C";
			}else document.getElementById(id).style.background = "#FFFFFF";
		}
	}
}

//muestra u oculta la fila de putts
function muestraPutts(grande)
{
	if(document.getElementById('putts').checked==true)
	{
		document.getElementById('label_putts').style.visibility="visible";
		document.getElementById('label_girs').style.visibility="visible";
		//si el campo tiene 18 hoyos
		if(grande==1)
		{
			document.getElementById('putts_1_9').style.visibility="visible";
			document.getElementById('putts_10_18').style.visibility="visible";
			document.getElementById('girs_1_9').style.visibility="visible";
			document.getElementById('girs_10_18').style.visibility="visible";
		}
		else
		{
			if(document.getElementById('num_forats').value == '9_9'){
				document.getElementById('putts_1_9').style.visibility="visible";
				document.getElementById('girs_1_9').style.visibility="visible";
			}else if(document.getElementById('num_forats').value == '9_18'){
				document.getElementById('putts_10_18').style.visibility="visible";
				document.getElementById('girs_10_18').style.visibility="visible";
			}
		}
	}
	else
	{
		document.getElementById('label_putts').style.visibility="hidden";
		document.getElementById('label_girs').style.visibility="hidden";
		document.getElementById('putts_1_9').style.visibility="hidden";
		document.getElementById('putts_10_18').style.visibility="hidden";
		document.getElementById('girs_1_9').style.visibility="hidden";
		document.getElementById('girs_10_18').style.visibility="hidden";
	}
	
}

//muestra u oculta la fila de palos
function muestraPalos(grande)
{
	if(document.getElementById('palos').checked==true)
	{
		$('.footer_fila_buida').addClass('footer-height');
		document.getElementById('label_palos').style.visibility="visible";
		//si el campo tiene 18 hoyos
		if(grande==1)
		{
			document.getElementById('palos_1_9').style.visibility="visible";
			document.getElementById('palos_10_18').style.visibility="visible";
		}
		else
		{
			if(document.getElementById('num_forats').value == '9_9'){
				document.getElementById('palos_1_9').style.visibility="visible";
			}else if(document.getElementById('num_forats').value == '9_18'){
				document.getElementById('palos_10_18').style.visibility="visible";
			}
		}
	}
	else
	{
		$('.footer_fila_buida').removeClass('footer-height');
		document.getElementById('label_palos').style.visibility="hidden";
		document.getElementById('palos_1_9').style.visibility="hidden";
		document.getElementById('palos_10_18').style.visibility="hidden";
	}
	
}

// funcio per mostrar la capa de seleccio de pals
function show_pals(id_input){
	document.getElementById('div_'+id_input).style.visibility="visible";
}

// uncio per amagar la capa de seleccio de pals
function hide_pals(id_input){
	document.getElementById('div_'+id_input).style.visibility="hidden";
}

// funcio per escollir un pal
function select_pal(elem){
	var choice = elem.innerHTML;
	var div_pal = elem.parentNode.parentNode.parentNode.getAttribute('rel');
	//alert(div_pal);
	if(document.getElementById(div_pal)){
		if(choice == '&nbsp;') choice = '';
		document.getElementById(div_pal).value = choice;
		hide_pals(div_pal);
	}else{
		//alert('ko');
	}
}

//muestra u oculta la fila de fairways
function muestraFairways(grande)
{
	if(document.getElementById('fairways').checked==true)
	{
		document.getElementById('label_fairways').style.visibility="visible";
		//si el campo tiene 18 hoyos
		if(grande==1)
		{
			document.getElementById('fairways_1_9').style.visibility="visible";
			document.getElementById('fairways_10_18').style.visibility="visible";
		}
		else
		{
			if(document.getElementById('num_forats').value == '9_9'){
				document.getElementById('fairways_1_9').style.visibility="visible";
			}else if(document.getElementById('num_forats').value == '9_18'){
				document.getElementById('fairways_10_18').style.visibility="visible";
			}
		}
	}
	else
	{
		document.getElementById('label_fairways').style.visibility="hidden";
		document.getElementById('fairways_1_9').style.visibility="hidden";
		document.getElementById('fairways_10_18').style.visibility="hidden";
	}
	
}

//muestra u oculta la fila de putts en puntuaciones de grupo
function muestraPutts_grupo()
{
	var num_jugadors = document.getElementById('num_jugadors').value;
	var cont = 1;
	
	if(document.getElementById('putts').checked==true)
	{
		for(cont=1;cont<=num_jugadors;cont++){
			document.getElementById('label_putts_'+cont).style.visibility="visible";
			document.getElementById('label_girs_'+cont).style.visibility="visible";
			document.getElementById('putts_1_9_'+cont).style.visibility="visible";
			document.getElementById('putts_10_18_'+cont).style.visibility="visible";
			document.getElementById('girs_1_9_'+cont).style.visibility="visible";
			document.getElementById('girs_10_18_'+cont).style.visibility="visible";
		}
	}
	else
	{
		for(cont=1;cont<=num_jugadors;cont++){
			document.getElementById('label_putts_'+cont).style.visibility="hidden";
			document.getElementById('label_girs_'+cont).style.visibility="hidden";
			document.getElementById('putts_1_9_'+cont).style.visibility="hidden";
			document.getElementById('putts_10_18_'+cont).style.visibility="hidden";
			document.getElementById('girs_1_9_'+cont).style.visibility="hidden";
			document.getElementById('girs_10_18_'+cont).style.visibility="hidden";
		}
	}
	
}

//muestra u oculta la fila de fairways en puntuaciones de grupo
function muestraFairways_grupo()
{
	var num_jugadors = document.getElementById('num_jugadors').value;
	var cont = 1;
	
	if(document.getElementById('fairways').checked==true)
	{
		for(cont=1;cont<=num_jugadors;cont++){
			document.getElementById('label_fairways_'+cont).style.visibility="visible";
			document.getElementById('fairways_1_9_'+cont).style.visibility="visible";
			document.getElementById('fairways_10_18_'+cont).style.visibility="visible";
		}
	}
	else
	{
		for(cont=1;cont<=num_jugadors;cont++){
			document.getElementById('label_fairways_'+cont).style.visibility="hidden";
			document.getElementById('fairways_1_9_'+cont).style.visibility="hidden";
			document.getElementById('fairways_10_18_'+cont).style.visibility="hidden";
		}
	}
	
}


function num_9()
{
	if(document.getElementById('h_9').checked==true)
	{	
		document.getElementById('div_10_18').style.display = "none";
		document.getElementById('div_1_9').style.display = "block";
		document.getElementById('div_1_18').style.display = "none";
		document.getElementById('h_18').checked=false;
		if(document.getElementById('num_forats'))
			document.getElementById('num_forats').value = document.getElementById('h_9').value;
	}
}

function num_18()
{
	if(document.getElementById('h_18').checked==true)
	{
		document.getElementById('div_10_18').style.display = "block";
		document.getElementById('div_1_9').style.display = "none";
		document.getElementById('div_1_18').style.display = "none";
		document.getElementById('h_9').checked=false;
		if(document.getElementById('num_forats'))
			document.getElementById('num_forats').value = document.getElementById('h_18').value;
	}
}

function num_all()
{
	if(document.getElementById('h_all').checked==true)
	{
		document.getElementById('div_1_9').style.display = "block";
		document.getElementById('div_10_18').style.display = "block";
		document.getElementById('div_1_18').style.display = "block";
		if(document.getElementById('num_forats'))
			document.getElementById('num_forats').value = document.getElementById('h_all').value;
	}
}

function select_all()
{
	document.getElementById('h_all').checked = true;
	document.getElementById('div_1_9').style.display = "block";
	document.getElementById('div_10_18').style.display = "block";
	document.getElementById('div_1_18').style.display = "block";
	if(document.getElementById('num_forats'))
		document.getElementById('num_forats').value = document.getElementById('h_all').value;
}

// funcio per comprovar que login i password tinguin un format valid
function valida_login(form){
	var usuari = form.usuari.value;
	var clau = form.pass.value;
	//var filtre=/^([a-zA-Z0-9@.])*$/;
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;   
	// mirem que no estiguin buits
	if( (usuari.length > 0) && (clau.length > 0) ){ 
		// comprovem el format
		//if( (filtre.test(usuari)) && (filtre.test(clau)) ){
		if (reg.test(usuari)!=false) {
			form.action = "autentifica.php";
			form.submit();
		}else{
			alert(login_password_invalido);
		}
	}
}


// funcio que actualitza l'estat dels radiobutton de seleccio de forats respecte la seleccio de la modalitat de puntuacio
function actualitza_radio_forats(valor){
	if(valor != null && valor > 0){
		switch(valor){
			case '1':
				document.getElementById('h_9').disabled = false;
				document.getElementById('h_18').disabled = false;
				document.getElementById('h_all').disabled = false;
			break;
			case '2':
				document.getElementById('h_9').disabled = true;
				document.getElementById('h_18').disabled = true;
				document.getElementById('h_all').disabled = true;
				document.getElementById('h_all').checked = true;
				num_all();
			break;
		}
	}
}

// funcio que consulta el handicap del jugador escollit en les puntuacions de grup
function query_hcp_jugador(num_select,id_jugador){
	if(num_select!=null && id_jugador!=null){
		var tipus_camp = document.getElementById('tipus_camp').value;
		//var crida = "ajax-consulta-handicap.php?target=hcp_jugador_"+num_select+"&id_jugador="+id_jugador+"&tipus="+tipus_camp;
		//cridaAJAX(crida);
		FAjax_input('ajax-consulta-handicap.php','hcp_jugador_'+num_select,'id_jugador='+id_jugador+'&tipus='+tipus_camp,'post');
	}
}

//validacion del formulario de ajax_puntuacions_tees
function valida_puntuacions(form, grande, nuevo){

	//miramos que se haya introducido una fecha
	if(document.getElementById('f_date_c_fecha_puntuacions').value=='')
	{
		alert(fecha_obligatoria);
		return (false);
	}
	
	
	//validació del handicap
	var handicap = Number(document.getElementById("handicap").value);
	document.getElementById("handicap").value=handicap.toFixed(1);
	if(handicap>99 || handicap<-10){
		alert(handicap_incorrecto);
		return (false);
	}

	
	// validacio de puntacions actual (1-9 o 10-18 o 1-18)
	
	//miramos que se haya marcado un numero de hoyos
	if(document.getElementById('h_9').checked==false && document.getElementById('h_18').checked==false && document.getElementById('h_all').checked==false)
	{
		alert(elegir_hoyos);
		return (false);
	}
	
	// si escogemos STABLEFORD solo controlamos los putts (opcionales)
	if(document.getElementById('modalitat').value==2){
		for(i=1; i<=18; i++){
			//si esta seleccionado "introducir putts"
			if(document.getElementById('putts')){
				if(document.getElementById('putts').checked==true)
				{
					if(document.getElementById('putt'+i).value=='')
					{
						alert(rellenar_18putts);
						return (false);
					}
				}
			}
		}
		if(!confirm(confirm_stableford)){
			return (false);
		}
	}else{
	// sino, validacion clasica de puntuaciones (todos los golpes > 0 y todos los putts opcionales rellenados admitiendo 0)
		//si hemos elegido 1-9
		if(document.getElementById('h_9').checked==true)
		{
			//miramos que la 1º fila este completa
			for(i=1; i<=9; i++)
			{
				if(document.getElementById('golpe'+i).value=='' || document.getElementById('golpe'+i).value==0)
				{
					alert(rellenar_fila_completa);
					return (false);
				}
				//si esta seleccionado "introducir putts"
				if(document.getElementById('putts')){
					if(document.getElementById('putts').checked==true)
					{
						if(document.getElementById('putt'+i).value=='')
						{
						alert(rellenar_putts);
						return (false);
						}
						
					}
				}
			}
		//si hemos elegido 10-18	
		}else if(document.getElementById('h_18').checked==true){
			//miramos que la 2º fila este completa
			for(i=10; i<=18; i++)
			{
				if(document.getElementById('golpe'+i).value=='' || document.getElementById('golpe'+i).value==0)
				{
					alert(rellenar_fila_completa);
					return (false);
				}
				//si esta seleccionado "introducir putts"
				if(document.getElementById('putts')){
					if(document.getElementById('putts').checked==true)
					{
						if(document.getElementById('putt'+i).value=='')
						{
						alert(rellenar_putts);
						return (false);
						}
						
					}
				}
			}
		//si hemos elegido los 18 hoyos, tienen que tener valor todos
		}else if(document.getElementById('h_all').checked==true){
			for(i=1; i<=18; i++)
			{
				if(document.getElementById('golpe'+i).value=='' || document.getElementById('golpe'+i).value==0)
				{
					alert(rellenar_18golpes);
					return (false);
				}
				//si esta seleccionado "introducir putts"
				if(document.getElementById('putts')){
					if(document.getElementById('putts').checked==true)
					{
						if(document.getElementById('putt'+i).value=='')
						{
							alert(rellenar_18putts);
							return (false);
						}
					}
				}
			}	
		}
	}
	
	if(nuevo==1)
	{
		document.form_puntacions.data_puntuacio.value = document.getElementById('f_date_c_fecha_puntuacions').value;
		document.form_puntacions.tipus_tee.value = document.getElementById('tee').value;
		document.form_puntacions.id_modalitat.value = document.getElementById('modalitat').value;
		document.form_puntacions.handicap_usuari.value = document.getElementById('handicap').value;
		if(document.getElementById('competicion')){
			if(document.getElementById('competicion').checked)
				document.form_puntacions.flag_competicio.value = 1;
			else
				document.form_puntacions.flag_competicio.value = 0;
		}
		if(document.getElementById('putts').checked){
			document.form_puntacions.flag_putts.value = 1;
		}else{
			document.form_puntacions.flag_putts.value = 0;
		}
		if(document.getElementById('palos').checked){
			document.form_puntacions.flag_palos.value = 1;
		}else{
			document.form_puntacions.flag_palos.value = 0;
		}
		if(document.getElementById('fairways')){
			if(document.getElementById('fairways').checked)
				document.form_puntacions.flag_fairways.value = 1;
			else
				document.form_puntacions.flag_fairways.value = 0;
		}
		document.form_puntacions.comentaris_partida.value = document.getElementById('comentarios').value;
		if(document.getElementById('visible')){
			if(document.getElementById('visible').checked)
				document.form_puntacions.flag_visible.value = 1;
			else
				document.form_puntacions.flag_visible.value = 0;
		}
		document.form_puntacions.action = "bd_introducir_puntuacions.php";
		//alert(document.form_puntacions.golpe1.value);
		document.form_puntacions.submit();
	}
	else
	{
		document.form_puntacions.data_puntuacio.value = document.getElementById('f_date_c_fecha_puntuacions').value;
		document.form_puntacions.tipus_tee.value = document.getElementById('tee').value;
		document.form_puntacions.id_modalitat.value = document.getElementById('modalitat').value;
		document.form_puntacions.handicap_usuari.value = document.getElementById('handicap').value;
		if(document.getElementById('competicion')){
			if(document.getElementById('competicion').checked)
				document.form_puntacions.flag_competicio.value = 1;
			else
				document.form_puntacions.flag_competicio.value = 0;
		}
		if(document.getElementById('putts').checked){
			document.form_puntacions.flag_putts.value = 1;
		}else{
			document.form_puntacions.flag_putts.value = 0;
		}
		if(document.getElementById('palos').checked){
			document.form_puntacions.flag_palos.value = 1;
		}else{
			document.form_puntacions.flag_palos.value = 0;
		}
		if(document.getElementById('fairways')){
			if(document.getElementById('fairways').checked)
				document.form_puntacions.flag_fairways.value = 1;
			else
				document.form_puntacions.flag_fairways.value = 0;
		}
		document.form_puntacions.comentaris_partida.value = document.getElementById('comentarios').value;
		if(document.getElementById('visible')){
			if(document.getElementById('visible').checked)
				document.form_puntacions.flag_visible.value = 1;
			else
				document.form_puntacions.flag_visible.value = 0;
		}
		document.form_puntacions.action = "bd_edit_puntuacion.php";
		//alert(document.form_puntacions.tipus_tee.value);
		document.form_puntacions.submit();	
	}
		
}

//validacion del formulario de ajax_puntuacions_tees per a puntuacions de GRUP
function valida_puntuacions_grup(form, grande, nuevo){

	//miramos que se haya introducido una fecha
	if(document.getElementById('f_date_c_fecha_puntuacions').value=='')
	{
		alert(fecha_obligatoria);
		return (false);
	}
	
	var num_jugadors = document.getElementById('num_jugadors_partida').value;
	
	if(num_jugadors > 1){
		// validacio de puntacions actual (1-9 o 10-18 o 1-18)
	
		//miramos que se haya marcado un numero de hoyos
		if(document.getElementById('h_9').checked==false && document.getElementById('h_18').checked==false && document.getElementById('h_all').checked==false)
		{
			alert(elegir_hoyos);
			return (false);
		}
		
		// comprovem que s'hagin escollit tots els jugadors
		for(j=1; j<=num_jugadors; j++){
			if(document.getElementById('select_jugador_'+j).value == 0){
				alert("Debe seleccionar los "+num_jugadors+" jugadores");
				return (false);
			}
		}
		
		// comprovem que no s'hagi repetit cap jugador
		for(j=1; j<=num_jugadors; j++){
			for(l=1; l<=num_jugadors; l++){
				if(l != j){
					if(document.getElementById('select_jugador_'+l).value == document.getElementById('select_jugador_'+j).value){
						alert(jugadores_repetidos);
						return (false);
					}
				}
			}
		}
		
		// comprovem que s'hagin omplert tots els handicaps
		for(j=1; j<=num_jugadors; j++){
			if(document.getElementById('hcp_jugador_'+j).value.length==0 || isNaN(document.getElementById('hcp_jugador_'+j).value)){
				alert("Debe rellenar el handicap de los "+num_jugadors+" jugadores");
				return (false);
			}else{
				var handicap = Number(document.getElementById('hcp_jugador_'+j).value);
				document.getElementById('hcp_jugador_'+j).value=handicap.toFixed(1);
				if(handicap>99 || handicap<-10){
					alert(handicap_incorrecto);
					document.getElementById('hcp_jugador_'+j).style.border="1px solid red";
					return (false);
				}else{
					document.getElementById('hcp_jugador_'+j).style.border="1px solid #CCCCCC";
				}
			}
		}
		
		// si escogemos STABLEFORD solo controlamos los putts (opcionales)
		if(document.getElementById('modalitat').value==2){
			for(j=1; j<=num_jugadors; j++){
				for(i=1; i<=18; i++){
					//si esta seleccionado "introducir putts"
					if(document.getElementById('putts')){
						if(document.getElementById('putts').checked==true)
						{
							if(document.getElementById('putt'+i+'_'+j).value=='')
							{
								alert(rellenar_putts);
								return (false);
							}
						}
					}
				}
			}
			if(!confirm(confirm_stableford)){
				return (false);
			}
		}else{
		
			//si hemos elegido 1-9
			if(document.getElementById('h_9').checked==true)
			{
				
				// comprovem que s'hagi omplert tota la fila de cops per cada jugador
				for(j=1; j<=num_jugadors; j++){
					for(i=1; i<=9; i++){
						if(document.getElementById('golpe'+i+'_'+j).value=='' || document.getElementById('golpe'+i+'_'+j).value==0){
							alert(rellenar_fila_completa);
							return (false);
						}else{
							//si esta seleccionado "introducir putts"
							if(document.getElementById('putts')){
								if(document.getElementById('putts').checked==true)
								{
									if(document.getElementById('putt'+i+'_'+j).value=='')
									{
									alert(rellenar_putts);
									return (false);
									}
								}
							}
							
						}
					}	
				}
						
				
			//si hemos elegido 10-18	
			}else if(document.getElementById('h_18').checked==true){
				
				// comprovem que s'hagi omplert tota la fila de cops per cada jugador
				for(j=1; j<=num_jugadors; j++){
					for(i=10; i<=18; i++){
						if(document.getElementById('golpe'+i+'_'+j).value=='' || document.getElementById('golpe'+i+'_'+j).value==0){
							alert(rellenar_fila_completa);
							return (false);
						}else{
							//si esta seleccionado "introducir putts"
							if(document.getElementById('putts')){
								if(document.getElementById('putts').checked==true)
								{
									if(document.getElementById('putt'+i+'_'+j).value=='')
									{
									alert(rellenar_putts);
									return (false);
									}
								}
							}
							
						}
					}	
				}
				
			//si hemos elegido los 18 hoyos, tienen que tener valor todos
			}else if(document.getElementById('h_all').checked==true){
				
				// comprovem que s'hagi omplert tota la fila de cops per cada jugador
				for(j=1; j<=num_jugadors; j++){
					for(i=1; i<=18; i++){
						if(document.getElementById('golpe'+i+'_'+j).value=='' || document.getElementById('golpe'+i+'_'+j).value==0){
							alert(rellenar_fila_completa);
							return (false);
						}else{
							//si esta seleccionado "introducir putts"
							if(document.getElementById('putts')){
								if(document.getElementById('putts').checked==true)
								{
									if(document.getElementById('putt'+i+'_'+j).value=='')
									{
									alert(rellenar_putts);
									return (false);
									}
								}
							}
							
						}
					}
				}
				
			}
		}
		
		if(nuevo==1)
		{
			document.form_puntacions.data_puntuacio.value = document.getElementById('f_date_c_fecha_puntuacions').value;
			document.form_puntacions.tipus_tee.value = document.getElementById('tee').value;
			document.form_puntacions.id_modalitat.value = document.getElementById('modalitat').value;
			
			if(document.getElementById('putts').checked){
				document.form_puntacions.flag_putts.value = 1;
			}else{
				document.form_puntacions.flag_putts.value = 0;
			}
			if(document.getElementById('fairways')){
				if(document.getElementById('fairways').checked)
					document.form_puntacions.flag_fairways.value = 1;
				else
					document.form_puntacions.flag_fairways.value = 0;
			}
			document.form_puntacions.comentaris_partida.value = document.getElementById('comentarios').value;
			document.form_puntacions.action = "bd_introducir_puntuacions_grup.php";
			document.form_puntacions.submit();
		
		}
		
	}else alert(jugadores_incorrecto);
	
}


//validacion del formulario d'editar_puntuacion.php per puntuacions de grup
function valida_puntuacions_grup_edit(form, grande){

	//miramos que se haya introducido una fecha
	if(document.getElementById('f_date_c_fecha_puntuacions').value=='')
	{
		alert(fecha_obligatoria);
		return (false);
	}
	
	
	// validacio de puntacions actual (1-9 o 10-18 o 1-18)
	
	//miramos que se haya marcado un numero de hoyos
	if(document.getElementById('h_9').checked==false && document.getElementById('h_18').checked==false && document.getElementById('h_all').checked==false)
	{
		alert(elegir_hoyos);
		return (false);
	}
	
	// comprovem que s'hagi omplert el handicap
	if(document.getElementById('handicap_edit')){
		if(document.getElementById('handicap_edit').value.length==0 || isNaN(document.getElementById('handicap_edit').value)){
			alert("Debe rellenar el handicap");
			return (false);
		}else{
			var handicap = Number(document.getElementById('handicap_edit').value);
			document.getElementById('handicap_edit').value=handicap.toFixed(1);
			if(handicap>99 || handicap<-10){
				alert(handicap_incorrecto);
				document.getElementById('handicap_edit').style.border="1px solid red";
				return (false);
			}else{
				document.getElementById('handicap_edit').style.border="1px solid #CCCCCC";
				document.getElementById('handicap').value = document.getElementById('handicap_edit').value;
			}
		}
	}
		
	// si escogemos STABLEFORD solo controlamos los putts (opcionales)
	if(document.getElementById('id_modalitat').value==2){
		for(i=1; i<=18; i++){
			//si esta seleccionado "introducir putts"
			if(document.getElementById('putts')){
				if(document.getElementById('putts').checked==true)
				{
					if(document.getElementById('putt'+i).value=='')
					{
						alert(rellenar_putts);
						return (false);
					}
				}
			}
		}
		if(!confirm(confirm_stableford)){
			return (false);
		}
	
	}else{
		//si hemos elegido 1-9
		if(document.getElementById('h_9').checked==true)
		{
					//miramos que la 1º fila este completa
					for(i=1; i<=9; i++)
					{
						if(document.getElementById('golpe'+i).value=='' || document.getElementById('golpe'+i).value==0)
						{
							alert(rellenar_fila_completa);
							return (false);
						}else{
							
							//si esta seleccionado "introducir putts"
							if(document.getElementById('putts')){
								if(document.getElementById('putts').checked==true)
								{
									if(document.getElementById('putt'+i).value=='')
									{
									alert(rellenar_putts);
									return (false);
									}
								}
							}
						}
						
					}	

		//si hemos elegido 10-18	
		}else if(document.getElementById('h_18').checked==true){
					//miramos que la 2º fila este completa
					for(i=10; i<=18; i++)
					{
						if(document.getElementById('golpe'+i).value=='' || document.getElementById('golpe'+i).value==0)
						{
							alert(rellenar_fila_completa);
							return (false);
						}else{
							
							//si esta seleccionado "introducir putts"
							if(document.getElementById('putts')){
								if(document.getElementById('putts').checked==true)
								{
									if(document.getElementById('putt'+i).value=='')
									{
									alert(rellenar_putts);
									return (false);
									}
								}
							}
						}
						
					}				
		//si hemos elegido los 18 hoyos, tienen que tener valor todos
		}else if(document.getElementById('h_all').checked==true){
			for(i=1; i<=18; i++)
			{
				if(document.getElementById('golpe'+i).value=='' || document.getElementById('golpe'+i).value==0)
				{
					alert(rellenar_18golpes);
					return (false);
				}else{
							
					//si esta seleccionado "introducir putts"
					if(document.getElementById('putts')){
						if(document.getElementById('putts').checked==true)
						{
							if(document.getElementById('putt'+i).value=='')
							{
							alert(rellenar_putts);
							return (false);
							}
						}
					}
				}
				
			}	
		}
	}
	
	form.comentaris_partida.value = document.getElementById("comentarios").value;	
	form.action = "bd_edit_puntuacio_grup.php";
	form.submit();	
	
}


//recarga de provincias dependiendo del pais
function actualitza_provincies(form){
	// array d'inputs del formulari
	var inputs = form.getElementsByTagName('select');
	// array de formacions marcades
	var id_provincies = new Array();
	var crida = "ajax_provincies.php?target=capa_provincies&paisos=";
	var j=0;
			
	for(var i=0; i<inputs.length; i++ ){
			if(inputs[i].name == "pais"){
				if(inputs[i].value.length != 0){
					id_provincies[j] = inputs[i].value;
					j++;
				}
			}
	}
	if(id_provincies.length > 0){
		for(var k=0; k<id_provincies.length; k++)
		{
		crida += id_provincies[k]+",";
		}
		//alert(crida);
		cridaAJAX(crida);
	}else document.getElementById('capa_provincies').innerHTML = '<span style="color:#666666" >Cal marcar el país </span>';
}



//comprueba si el mail existe en la bd
function comprueba_login(form,portada){
	if(document.getElementById('login').value.length > 0 && comprovaEmail(document.getElementById('login').value))
	{
			var login_actual = document.getElementById('login').value;
			var crida = "ajax_login.php?target=capa_ya_existe&portada="+portada+"&nick=";
			crida += login_actual;
			cridaAJAX(crida);

	}else{
		document.getElementById('capa_ya_existe').innerHTML = '<img src="img/xsmall.png" width="9" height="9" /><input type="hidden" name="login_hidden" id="login_hidden" value="0"  />';
	}
}

//comprueba si el nick existe en la bd
function comprueba_nick(form,portada){
	if(document.getElementById('nick').value.length > 0)
	{
		var nick_actual = document.getElementById('nick').value;
		if(nick_actual.indexOf('.') != -1){
			document.getElementById('capa_ya_existe_nick').innerHTML = '<img src="img/xsmall.png" width="9" height="9" /><input type="hidden" name="nick_hidden" id="nick_hidden" value="0"  />';
		}else{
			var crida = "ajax_nick.php?target=capa_ya_existe_nick&portada="+portada+"&nick=";
			crida += nick_actual;
			cridaAJAX(crida);
		}
	}else{
		document.getElementById('capa_ya_existe_nick').innerHTML = '<img src="img/xsmall.png" width="9" height="9" /><input type="hidden" name="nick_hidden" id="nick_hidden" value="0"  />';
	}
}

//validacion del formulario de registro
function valida_registre_nou(){
	
	var tot_ok = true;
	
	if(document.getElementById('nick').value.length == 0)
	{
		alert(nick_obligatorio);
		document.getElementById("nick").focus();
		tot_ok = false;
		return (false);
	}

	if(document.getElementById('login').value.length == 0)
	{
		alert(email_obligatorio);
		document.getElementById("login").focus();
		tot_ok = false;
		return (false);
	}	
	else
	{
		if(!comprovaEmail(document.getElementById('login').value))
		{
			alert(email_invalido);
			document.getElementById("login").focus();
			tot_ok = false;
			return (false);
		}
	}

	if(document.getElementById('contrasenya').value == 0){
		alert(password_obligatorio);
		document.getElementById("contrasenya").focus();
		tot_ok = false;
		return (false);
	}
	
	if(tot_ok == true && document.getElementById('login_hidden').value!='0' &&  document.getElementById('nick_hidden').value!='0' ) {
		document.form_registro_express.action = "registro.php";
		document.form_registro_express.submit();
	}
	
}

//validacion del formulario de registro
function valida_registro(form, nuevo){
	
	var tot_ok = true;
	
	if(document.getElementById('nom').value.length == 0)
	{
		alert(nombre_obligatorio);
		document.getElementById("nom").focus();
		tot_ok = false;
		return (false);
	}

	if(document.getElementById('cognoms').value.length == 0)
	{
		alert(apellido_obligatorio);
		document.getElementById("cognoms").focus();
		tot_ok = false;
		return (false);
	}
	
	if(document.getElementById('nick').value.length == 0)
	{
		alert(nick_obligatorio);
		document.getElementById("nick").focus();
		tot_ok = false;
		return (false);
	}
	
	if(document.getElementById('fecha_nacimiento').value.length > 0)
	{
		var regx_fecha = /(0[1-9]|[12][0-9]|3[01])[/](0[1-9]|1[012])[/](19|20)\d\d/; //regular expresion fecha

	   if( !regx_fecha.test(document.getElementById('fecha_nacimiento').value)){
			alert(fecha_invalida);
			document.getElementById("fecha_nacimiento").focus();
			tot_ok = false;
			return (false);
		}
	}
	
	//alert(nuevo);
	if (nuevo==1)
		{
			if(document.getElementById('login').value.length == 0)
			{
			alert(email_obligatorio);
			document.getElementById("login").focus();
			tot_ok = false;
			return (false);
			}	
			else
			{
				if(!comprovaEmail(document.getElementById('login').value))
				{
					alert(email_invalido);
					document.getElementById("login").focus();
					tot_ok = false;
					return (false);
				}
			}
			
			if(document.getElementById('password').value == 0){
				alert(password_obligatorio);
				document.getElementById("password").focus();
				tot_ok = false;
				return (false);
			}
			
		}
		
	
	/*
	if(document.getElementById('password').value.length == 0)
	{
		alert("Introduzca un password");
		document.getElementById("password").focus();
		return (false);
	}
	
	if(document.getElementById('password2').value.length == 0)
	{
		alert("Repita el password");
		document.getElementById("password2").focus();
		return (false);
	}
	*/
	
	if(document.getElementById('password').value!=document.getElementById('password2').value)
	{
		alert(passwords_diferentes);
		document.getElementById("password").focus();
		tot_ok = false;
		return (false);
	}
	
	if(document.getElementById('provincia')){
		if(document.getElementById('provincia').value == ""){
			alert(provincia_obligatoria);
			document.getElementById("movil").focus();
			tot_ok = false;
			return (false);
		}
	}
	
	if(document.getElementById('movil').value.length != 0)
	{
		if(document.getElementById('movil').value.length !=9 )
		{
			alert(movil_invalido);
			document.getElementById("movil").focus();
			tot_ok = false;
			return (false);
		}
	}
	
	
	if(tot_ok == true && document.getElementById('login_hidden').value!='0' &&  document.getElementById('nick_hidden').value!='0' ){
		document.getElementById('registrar').onclick = 'return(false);';
		form.action = "bd_jugador_dades.php";
		form.submit();
	}
	
}

/*****************************************************SET NICKNAME VICTOR*********************************************************************/
//validacion del formulario de registro
function valida_registro_nick(form){
	
	var tot_ok = true;
	
	if(document.getElementById('nick').value.length == 0)
	{
		alert(nick_obligatorio);
		document.getElementById("nick").focus();
		tot_ok = false;
		return (false);
	}
	
	if(tot_ok == true && document.getElementById('nick_hidden').value!='0' ){
		form.action = "update-nickname.php";
		form.submit();
	}
	
}
/**********************************************************************************************************************************************/


// validacion del formato del correo electronico
function comprovaEmail(mail){
	var filtre=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
	var resultat = false;
	
	if (mail.length > 0){
		if (filtre.test(mail)){
			resultat=true
		}
	}
	return resultat;
}


//funcion para controlar que sólo se inserten números, enter o  símbolo + y permite borrar
//var nav4 = window.Event ? true : false;
function acceptNum(ev){
// NOTE: Backspace = 8, Enter = 13, '0' = 48, '9' = 57, + = 43
	//var key = nav4 ? evt.which : evt.keyCode;
	// CODI ADAPTAT PERQUE FUNCIONI EN IE8
	var key; 
	if(window.event){ 
		key = ev.keyCode;
	}
	else if(event.which){ 
		key = ev.which;
	} 
	if(key==undefined){ // si el codi de la tecla es undefined vol dir que estem a FF i apliquem el codi antic
		//alert('undefined');
		var nav4 = window.Event ? true : false;
		key = nav4 ? ev.which : ev.keyCode;
	}
	return ( key <= 13 || (key >= 48 && key <= 57) || key == 43 );
}

//funcion para controlar que sólo se inserten números o enter
function acceptNum_only(event){
// NOTE: Backspace = 8, Enter = 13, '0' = 48, '9' = 57
	//var key = nav4 ? evt.which : evt.keyCode;
	// CODI ADAPTAT PERQUE FUNCIONI EN IE8
	var key; 
	if(window.event){ 
		key = event.keyCode;
	}
	else if(event.which){ 
		key = event.which;
	} 
	//alert(key);
	if(key==undefined){ // si el codi de la tecla es undefined vol dir que estem a FF i apliquem el codi antic
		//alert('undefined');
		var nav4 = window.Event ? true : false;
		key = nav4 ? event.which : event.keyCode;
	}
	return ( key <= 13 || (key >= 48 && key <= 57) );
}

function acceptNumDecimals_only(event){
// NOTE: Delete = 8, . = 190, Enter = 13, '0' = 48, '9' = 57
	/*
	var key = nav4 ? evt.which : evt.keyCode;
	*/
	// CODI ADAPTAT PERQUE FUNCIONI EN IE8
	var key; 
	if(window.event){ 
		key = event.keyCode;
	}
	else if(event.which){ 
		key = event.which;
	} 
	if(key==undefined){ // si el codi de la tecla es undefined vol dir que estem a FF i apliquem el codi antic
		//alert('undefined');
		var nav4 = window.Event ? true : false;
		key = nav4 ? event.which : event.keyCode;
	}
	//alert(key);
	return ( key <= 13 || key == 45 || key == 46 || key == 190 || (key >= 48 && key <= 57) );
}

function elimina_logo(id_grup)
	{
	if(confirm("¿Seguro que quiere eliminar el logo?")){
		elimina_logo_grup(id_grup);
	}
}


function elimina_logo_grup(id_grup){
	var crida="esborra_logo_grup.php?";
	if(typeof id_grup != "undefined") crida+="id="+id_grup;
	cridaAJAX3(crida);
}

function amagaFoto(id2)
	{
	if(confirm("¿Seguro que quiere borrar la imagen?")){
		eliminaImatgeEvent(id2);
	}
}


function eliminaImatgeEvent(id2){
	var crida="esborraFotoJugador.php?";
	if(typeof id2 != "undefined") crida+="id="+id2;
	cridaAJAX3(crida);
}

function cridaAJAX3(url){
	var httpRequest;		
	var params="";
	
	try{
		params=url.split('?')[1];
		url=url.split('?')[0];
	}catch(e){}
	
    if (window.XMLHttpRequest) { // Mozilla, Safari, ...
    	httpRequest = new XMLHttpRequest();
		if (httpRequest.overrideMimeType) {
			httpRequest.overrideMimeType('text/xml');
		}
    } else if (window.ActiveXObject) { // IE
    	try {
        	httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
            	httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
        }
    }
	
    if (!httpRequest) {
    	alert(error_ajax);
        return false;
    }
	
    httpRequest.onreadystatechange = function() { mostraResultat3(httpRequest); };
    httpRequest.open('GET', url+"?"+params, true);
    httpRequest.send(null);
}


function mostraResultat3(httpRequest) {
		if(httpRequest.readyState < 4){//loading
			
		}
        if (httpRequest.readyState == 4) {//la resposta un cop s'ha carregat
            if (httpRequest.status == 200) {
                // Mostrem la taula resultant
                resposta=httpRequest.responseText;
				if(resposta=="OK"){
					document.getElementById("foto").style.visibility = "hidden"; 
					document.getElementById("linkeliminar").style.visibility = "hidden"; 
					//alert(document.getElementById("load_imatge1").value);
					document.getElementById("foto_usu").value= '';
					//alert(document.getElementById("load_imatge1").value);
				}else alert(error_imagen);
				//alert(resposta);
                //document.getElementById(target).innerHTML=resposta;
            } else {
                alert(error_peticion);
            }
        }

    }
	
function cridaAJAX_EXCEL(url){
	var httpRequest;		
	var params="";
	
	try{
		params=url.split('?')[1];
		url=url.split('?')[0];
	}catch(e){}
	
    if (window.XMLHttpRequest) { // Mozilla, Safari, ...
    	httpRequest = new XMLHttpRequest();
		if (httpRequest.overrideMimeType) {
			httpRequest.overrideMimeType('text/xml');
		}
    } else if (window.ActiveXObject) { // IE
    	try {
        	httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
            	httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
        }
    }
	
    if (!httpRequest) {
    	alert(error_ajax);
        return false;
    }
	
    httpRequest.onreadystatechange = function() { mostraResultat_EXCEL(httpRequest); };
    httpRequest.open('GET', url+"?"+params, true);
    httpRequest.send(null);
}


function mostraResultat_EXCEL(httpRequest) {
		if(httpRequest.readyState < 4){//loading
			
		}
        if (httpRequest.readyState == 4) {//la resposta un cop s'ha carregat
            if (httpRequest.status == 200) {
                // Mostrem la taula resultant
                resposta=httpRequest.responseText;
				if(resposta=="KO"){
					alert(puntuaciones_inexistentes);
				}else{
					document.getElementById('form_exel').submit();
				}
            } else {
                alert(error_peticion);
            }
        }

    }
	
/*********************** Galeria de fotos de CAMP **********************/
function mostra_foto(id_foto_petita){
	//var src_imatge = "";
	//var num_carpetes = 0;
	
	
	
			
	
	
	
	if(document.getElementById('imatge_'+id_foto_petita)){
		imatge_petita = document.getElementById('imatge_'+id_foto_petita).src;
		imatge_gran = document.getElementById('imatge_principal').src;
		//num_carpetes = ruta_completa.split('/').length;
		//src_imatge = ruta_completa.split('/')[num_carpetes-1];
		//alert(document.getElementById('imatge_'+id_foto_petita).name);
		amplada = document.getElementById('imatge_'+id_foto_petita).alt.split(',')[0];
		alsada = document.getElementById('imatge_'+id_foto_petita).alt.split(',')[1];
		if(imatge_gran != imatge_petita){
			document.getElementById('imatge_principal').src = imatge_petita;
			//alert(document.getElementById('imatge_principal').width+','+document.getElementById('imatge_principal').height);
			//alert(amplada+','+alsada);
			if(amplada > 396) amplada = 396;	
			document.getElementById('imatge_principal').width = amplada;			
				
				
			if(alsada > 296) alsada = 296;	
			document.getElementById('imatge_principal').height = alsada;
			
			
			variableImagen = document.getElementById('imatge_principal');
			widthImagen = variableImagen.getAttribute('width');
			heightImagen = variableImagen.getAttribute('height');
			
			esquinasImagen = 24;
			
			widthFondoTotal = parseInt(widthImagen) + parseInt(esquinasImagen);
	
			document.getElementById('divtotal').style.width = widthFondoTotal + 'px';	
		
			document.getElementById('fondoSuperior').style.width = widthImagen + 'px';
			document.getElementById('fondoCentro').style.width = widthImagen + 'px';
			document.getElementById('fondoInferior').style.width = widthImagen + 'px';
			
			document.getElementById('fondoIzquierda').style.height = heightImagen + 'px';
			document.getElementById('fondoCentro').style.height = heightImagen + 'px';
			document.getElementById('fondoDerecha').style.height = heightImagen + 'px';
			
		}
		//document.getElementById('imatge_'+id_foto_petita).src = imatge_gran;
	}
}

function actualitza_llistat_camps(pais,provincia,pagina,total){
	var crida="ajax-llistat-camps.php?target=taula_camps";
	if( (typeof pais != "undefined") && (typeof provincia != "undefined") && (typeof pagina != "undefined") && (typeof total != "undefined") ){ 
		crida+="&pais="+pais;
		crida+="&p="+provincia;
		crida+="&pag="+pagina;
		crida+="&t="+total;
		//alert(crida);
		cridaAJAX_galeria_camp(crida);
	}
}

function actualitza_galeria(camp,pagina,total){
	var crida="ajax-galeria-camp.php?target=taula_galeria";
	if( (typeof camp != "undefined") && (typeof pagina != "undefined") && (typeof total != "undefined") ){ 
		crida+="&c="+camp;
		crida+="&p="+pagina;
		crida+="&t="+total;
		//alert(crida);
		cridaAJAX_galeria_camp(crida);
	}
}

function cridaAJAX_galeria_camp(url){
	var httpRequest;		
	var params="";
	
	try{
		params=url.split('?')[1];
		url=url.split('?')[0];
	}catch(e){}
	try{
		target=params.split('target=')[1].split('&')[0];	
	}catch(e){
		target="";	
	}
		
    if (window.XMLHttpRequest) { // Mozilla, Safari, ...
    	httpRequest = new XMLHttpRequest();
		if (httpRequest.overrideMimeType) {
			httpRequest.overrideMimeType('text/xml');
		}
    } else if (window.ActiveXObject) { // IE
    	try {
        	httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
            	httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
        }
    }
	
    if (!httpRequest) {
    	alert(error_ajax);
        return false;
    }
	
    httpRequest.onreadystatechange = function() { mostraResultat_galeria_camp(httpRequest,target); };
    httpRequest.open('GET', url+"?"+params, true);
    httpRequest.send(null);
}

function mostraResultat_galeria_camp(httpRequest,target) {
	
        if (httpRequest.readyState == 4) {//la resposta un cop s'ha carregat
            if (httpRequest.status == 200) {
                // Mostrem la taula resultant
                resposta=httpRequest.responseText;
				if(resposta!="KO"){
					document.getElementById(target).innerHTML = resposta;
				}
            } else {
                alert(error_peticion);
            }
        }
}

// funcio de paginacio dels millors resultats de la pagina CAMP
function actualitza_resultats_camp(camp,pagina,total,tipus){
	if(tipus == 1) target = "resultados";
	else if(tipus == 2) target = "resultados2";
	if( (camp != '') && (camp != undefined) && (camp != null)){
		var crida = "ajax-camp-resultats.php?target="+target+"&camp="+camp+"&pagina="+pagina+"&total="+total+"&llistat="+tipus;
		cridaAJAX_resultats_camp(crida,tipus);
	}
}

// funcio generica d'AJAX
function cridaAJAX_resultats_camp(url,tipus){
	var httpRequest;	
	var params="";

		try{
			params=url.split('?')[1];
			url=url.split('?')[0];
		}catch(e){}
		try{
			target=params.split('target=')[1].split('&')[0];
			
		}catch(e){
			target="";	
		}
        if (window.XMLHttpRequest) { // Mozilla, Safari, ...
            httpRequest = new XMLHttpRequest();
            if (httpRequest.overrideMimeType) {
                httpRequest.overrideMimeType('text/xml');
            }
        } else if (window.ActiveXObject) { // IE
            try {
                httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
            }
        }

        if (!httpRequest) {
            alert(error_ajax);
            return false;
        }
        httpRequest.onreadystatechange = function() { 
			mostraResultat_camp(httpRequest,target,tipus); 
		};
        httpRequest.open('GET', url+"?"+params, true);
        httpRequest.send(null);
}


function mostraResultat_camp(httpRequest,target,tipus) {
	if(httpRequest.readyState < 4){//loading
	}
    if (httpRequest.readyState == 4) {//la resposta un cop s'ha carregat 
        if (httpRequest.status == 200) {
            // Mostrem la taula resultant
            resposta=httpRequest.responseText;
			document.getElementById(target).innerHTML=resposta;
			if(tipus == 1)
				tb_init('a.thickbox_ajax');
			else if(tipus == 2)
				tb_init('a.thickbox_ajax2');
			else if(tipus == 3)
				tb_init('a.thickbox_ajax3');
			else if(tipus == 4)
				tb_init('a.thickbox_ajax4');
        } else {
            alert(error_peticion);
        }
    }

}

function valida_afegir_foto()
{
	//miramos que se haya introducido una foto
	if(document.getElementById('foto_usu').value=='')
	{
		alert(foto_invalida);
		return (false);
	}

	else
	{
		document.form_foto_camp.action = "bd_afegir_foto.php";
		document.form_foto_camp.submit();	
	}
}


function valida_lb_opinion(form,url_pagina){
	
	//miramos que se haya introducido un comentario
	if(document.getElementById('text_opinion').value=='')
	{
		alert(opinion_obligatorio);
		return (false);
	}	
	else
	{
		document.getElementById('text_opinion').value = ReplaceEnters(document.getElementById('text_opinion').value, true);
	   	var opinion=document.getElementById('text_opinion').value;
		var mail=document.getElementById('mail_opinion').value;
		document.getElementById('boton_lb_opinion').style.display = "none";
		document.getElementById('fila_boton').innerHTML = '<img src="img/ajax-loader.gif" id="cargando" name="cargando" width="25" />';
		
		var httpRequest;
			
		var url = "ajax_envio_opinion.php?text_opinion="+opinion+"&mail="+mail+"&seccio="+url_pagina;
		
        if (window.XMLHttpRequest) { // Mozilla, Safari, ...
            httpRequest = new XMLHttpRequest();
            if (httpRequest.overrideMimeType) {
                httpRequest.overrideMimeType('text/xml');
            }
        } else if (window.ActiveXObject) { // IE
            try {
                httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
            }
        }

        if (!httpRequest) {
            alert(error_ajax);
            return false;
        }
        httpRequest.onreadystatechange = function() { 
			//posicionaCapaLoading();
			//mostraCapaLoading();
			tanca_lightbox_opinio(httpRequest); 
		};
        httpRequest.open('GET', url, true);
        httpRequest.send(null);
		
	}
}


function tanca_lightbox_opinio(httpRequest) {
	//document.location.href="#top";
	if(httpRequest.readyState < 4){//loading
		//alert("estat igual a 1");
		//	document.getElementById("load").innerHTML="<img src=\"imatges/cargando.gif\" id=\"cargando\" name=\"cargando\" width=\"25\"/>";
		
		//setTimeout(doNext,15000);
	}
    if (httpRequest.readyState == 4) {//la resposta un cop s'ha carregat
		//setTimeout(amagaCapaLoading,1000); 
        if (httpRequest.status == 200) {
            // Mostrem la taula resultant
            resposta=httpRequest.responseText;
			//alert(resposta);
			self.parent.tb_remove();
        } else {
            alert(error_peticion);
        }
    }

}

//functio per actualitzar un qtip
function actualitzaQtip(e){
    qtip = e.qtip("api");
    qtip.updateContent($('#comentari').val());
    e.qtip("hide");
}

// validacio del canvi de dades dels incrits a un torneig
function guarda_inscripcio_horari(id_inscripcio){
	// aqui va tota la comprovacio
    var condicio=true;
    var text_alerta='';
    var handicap = $('#handicap').val().replace(",", ".");
    if($('#nom').val()!='' && $('#llicencia').val()!='' && $('#handicap').val()!='' && $('#hora').val()!=''){
        hora_pattern = /^([0-1][0-9]|[2][0-3]):([0-5][0-9])$/;
        if( !hora_pattern.test($('#hora').val())){
            text_alerta += alert_hora+'\n';
            condicio = false;
        }
        if($('#llicencia').val().length<10){
            text_alerta += alert_licencia+'\n';
            condicio = false;
        }
        if(isNaN(handicap)){
            text_alerta += alert_handicap+'\n';
            condicio = false;
        }else{
            if(handicap>99 || handicap<-10){
				text_alerta += handicap_incorrecto+'\n';
				condicio = false;
			}
        }
    }else{
        text_alerta += alert_camps_obligatoris;
        condicio = false;
    }
    if(text_alerta!=''){
        alert(text_alerta);
    }
    
    if(condicio){
        $.ajax({
    		type: "POST",
            //dataType: "text",
    		url: "ajax_inscripcio_horaris.php",
    		data: "id_inscripcio="+id_inscripcio+"&nom="+$('#nom').val()+"&llicencia="+$('#llicencia').val()+"&handicap="+handicap+"&hora="+$('#hora').val()+"&comentari="+$('#comentari').val() ,
    		beforeSend: function(){
    		},
    		success: function(data){
     		    if(data=='ok'){
                    parent.$('#'+id_inscripcio+' .fila_caixa_doble').html($('#nom').val());
                    parent.$('#'+id_inscripcio+' .fila_caixa .floatl').html($('#llicencia').val());
                    parent.$('#'+id_inscripcio+' .fila_caixa .floatr').html(handicap);
                    parent.$('#'+id_inscripcio+' .fila_caixa .hora_horaris').html($('#hora').val());
                    var element = parent.$('#'+id_inscripcio+' .fila_caixa .comentari');
                    if($('#comentari').val()!='' && $('#comentari').val()!='"" '){
                        actualitzaQtip(element);
                        parent.$(element).html('i');
                        parent.$(element).attr('style','display:block');
                    }else{
                        parent.$('#'+id_inscripcio+' .fila_caixa .comentari').html('');
                        parent.$(element).attr('style','display:none');
                    }              
                    self.parent.tb_remove();
                }
            }
    	 }); 
      }
}

// validacio del mail als inscrits a un torneig
function valida_lb_mail_torneo(form){
	// aqui va tota la comprovacio
	if(document.getElementById('text_mail').value.length > 0){
		var id_torneo = document.getElementById('id_torneo').value;
		var dia_torneo = document.getElementById('dia_torneo').value;
		var crida = 't='+id_torneo;
		if(dia_torneo > 0) crida += '&d='+dia_torneo;
		// amaguem el boto enviar
		document.getElementById('boto_enviar_mail').onclick = mostra_enviant;
		// enviem el mail
		FAjax_lightbox('ajax-mail-torneo.php',crida+'&c='+ReplaceEnters(document.getElementById('text_mail').value,true),'post');
		//self.parent.tb_remove();
	}else{
		alert(alert_text_buit);
	}
}

// validacio del lightbox per destacar un torneig
function destacar_torneo(id_torneo){
	if(document.getElementById('destacar_1').checked || document.getElementById('destacar_2').checked || document.getElementById('destacar_3').checked){
		var opcio = 0;
		if(document.getElementById('destacar_1').checked) opcio = 1;
		else if(document.getElementById('destacar_2').checked) opcio = 2;
		else if(document.getElementById('destacar_3').checked) opcio = 3;
		// amaguem el boto cancelar i canviem el d'enviar
		document.getElementById('boto_cancelar_torneig').style.display = 'none';
		document.getElementById('boto_destacar_torneig').onclick = mostra_enviant;
		// enviem el mail
		FAjax_lightbox('ajax-destacar-torneo.php','t='+id_torneo+'&opcio='+opcio,'post');
	}else{
		alert(alert_opcio_buida);
	}
}

function ReplaceEnters(texto, conbr) {
 //para que funcione en IE y Firefox
 var nl=document.all?String.fromCharCode(13):"\n";
 if (conbr) { 	
 	while(texto.indexOf(nl)>=0){
	  texto = texto.replace(nl, "<br />");
	  /*en IE aunque remplaces los char(13) los saltos se mantienen, debes hacer esto*/
	  if(document.all)  texto = texto.replace("\n", "");
	}
 } else {
	while(texto.indexOf("<br />")>=0){
	  texto = texto.replace("<br />",nl);
	}
 }
 return texto;
}


// funcio de paginacio del ultims resultats de la pagina de jugador detallat
function actualitza_ultims_resultats_jugador(jugador,pagina,total){
	var target = "capa_ultims_resultats";
	if( (jugador != '') && (jugador != undefined) && (jugador != null)){
		var crida = "ajax-jugador-detallat-resultats.php?target="+target+"&jugador="+jugador+"&pagina="+pagina+"&total="+total;
		cridaAJAX_resultats_camp(crida,3);
	}
}

// funcio de paginacio dels camps preferits de la pagina de jugador detallat
function actualitza_camps_jugador(jugador,pagina,total){
	var target = "capa_camps_preferits";
	if( (jugador != '') && (jugador != undefined) && (jugador != null)){
		var crida = "ajax-jugador-detallat-preferits.php?target="+target+"&jugador="+jugador+"&pagina="+pagina+"&total="+total;
		cridaAJAX_jugador_detallat(crida);
	}
}

// funcio de paginacio dels camps preferits de la pagina de jugador detallat
function actualitza_comentaris_jugador(jugador,pagina,total){
	var target = "star_2";
	if( (jugador != '') && (jugador != undefined) && (jugador != null)){
		var crida = "ajax-jugador-detallat-comentaris.php?target="+target+"&jugador="+jugador+"&pagina="+pagina+"&total="+total;
		cridaAJAX_resultats_camp(crida,4);
	}
}

// funcio generica d'AJAX
function cridaAJAX_jugador_detallat(url){
	var httpRequest;	
	var params="";

		try{
			params=url.split('?')[1];
			url=url.split('?')[0];
		}catch(e){}
		try{
			target=params.split('target=')[1].split('&')[0];
			
		}catch(e){
			target="";	
		}
        if (window.XMLHttpRequest) { // Mozilla, Safari, ...
            httpRequest = new XMLHttpRequest();
            if (httpRequest.overrideMimeType) {
                httpRequest.overrideMimeType('text/xml');
            }
        } else if (window.ActiveXObject) { // IE
            try {
                httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
            }
        }

        if (!httpRequest) {
            alert(error_ajax);
            return false;
        }
        httpRequest.onreadystatechange = function() { 
			mostraResultat_jugador_detallat(httpRequest,target); 
		};
        httpRequest.open('GET', url+"?"+params, true);
        httpRequest.send(null);
}

function mostraResultat_jugador_detallat(httpRequest,target) {
	if(httpRequest.readyState < 4){//loading
	}
    if (httpRequest.readyState == 4) {//la resposta un cop s'ha carregat 
        if (httpRequest.status == 200) {
            // Mostrem la taula resultant
            resposta=httpRequest.responseText;
			document.getElementById(target).innerHTML=resposta;
        } else {
            alert(error_peticion);
        }
    }

}


/*** esborrar puntuacio ****/
function esborrar_puntuacio(num_partida,id_jugador){
	if((num_partida != null) && (num_partida > 0) && (id_jugador != null) && (id_jugador > 0)){
		if(confirm("Seguro que quieres eliminar esta puntuación?")){
			document.location.href = "esborrar_puntuacio.php?p="+num_partida+"&j="+id_jugador;
		}
	}
}


/**** crear / editar un grup de jugadors ****/
//validacion del formulario de form-grup-nou
//function valida_grup(form){
function valida_grup(){
		
	if(document.getElementById('nom_grup').value.length == 0)
	{
		alert(nombre_grupo_obligatorio);
		document.getElementById("nom_grup").focus();
		return (false);
	}
	
	if(document.getElementById('nom_hidden').value != 0 ){
		document.getElementById('form_grup').action = "bd-grup-nou.php";
		document.getElementById('form_grup').submit();
		//alert("submit");
	}
}

function envia_edit_grup(form){	
	document.form_grup.action = "bd-edit-grup.php";
	document.form_grup.submit();
}

function init_mail_grup(){
	document.getElementById('mail_amic').value = "";
}

function convida_amic(id_grup){
	var mail = document.getElementById('mail_amic').value;
	var nom_grup = document.getElementById('nom_grup_hidden').value;
	if((id_grup != null) && (mail.length > 0)){
		if(comprovaEmail(mail)){
			var crida = "ajax-invitacio.php?mail="+mail+"&g="+id_grup+"&n="+nom_grup;
			cridaAJAX_invitacio(crida);
		}else{
			alert(email_invalido);
			document.getElementById('mail_amic').value = "Escribe e-mail";
		}
	}else document.getElementById('mail_amic').value = "Escribe e-mail";
	
}

// funcio generica d'AJAX
function cridaAJAX_invitacio(url){
	var httpRequest;	
	var params="";

		try{
			params=url.split('?')[1];
			url=url.split('?')[0];
		}catch(e){}
		try{
			target=params.split('target=')[1].split('&')[0];
			
		}catch(e){
			target="";	
		}
        if (window.XMLHttpRequest) { // Mozilla, Safari, ...
            httpRequest = new XMLHttpRequest();
            if (httpRequest.overrideMimeType) {
                httpRequest.overrideMimeType('text/xml');
            }
        } else if (window.ActiveXObject) { // IE
            try {
                httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
            }
        }

        if (!httpRequest) {
            alert(error_ajax);
            return false;
        }
        httpRequest.onreadystatechange = function() { 
			mostraResultat_invitacio(httpRequest,target); 
		};
        httpRequest.open('GET', url+"?"+params, true);
        httpRequest.send(null);
}

function mostraResultat_invitacio(httpRequest,target) {
	if(httpRequest.readyState < 4){//loading
	}
    if (httpRequest.readyState == 4) {//la resposta un cop s'ha carregat 
        if (httpRequest.status == 200) {
            // Mostrem la taula resultant
            resposta=httpRequest.responseText;
			//document.getElementById(target).innerHTML=resposta;
			alert(resposta);
			if(target != null){
				if(target == 'recargar'){
					window.location.reload();	
				}
			}
        } else {
            alert(error_peticion);
        }
    }

}

//comprueba si el nombre del grupo ya existe
function comprueba_grupo(){
	if(document.getElementById('nom_grup').value.length > 0)
	{
		var nom_grup = document.getElementById('nom_grup').value;
		var crida = "ajax-nom-grup.php?target=capa_ya_existe&nom_grup=";
		crida += nom_grup;
		cridaAJAX(crida);
	}else{
		document.getElementById('capa_ya_existe').innerHTML = '<img src="img/xsmall.png" width="9" height="9" /><input type="hidden" name="nom_hidden" id="nom_hidden" value="0"  />';
	}
}

// funcio per acceptar/rebutjar la invitacio a un grup
function respon_invitacio(grup,emissor,receptor,accio){
	// accio: ens diu si s'accepta o es rebutja la invitacio
	if((grup != null) && (emissor != null) && (receptor != null) && (accio != null)){
		var crida = "ajax-invitacio-resposta.php?target=recargar&g="+grup+"&e="+emissor+"&r="+receptor+"&a="+accio;
		cridaAJAX_invitacio(crida);
	}else{
		alert(error_invitacion);
	}
	
}

// funcio per amagar/mostrar els formularis d'introduir puntuacions individuals/grup
function comprova_selects_grup(){
	if(document.getElementById('result_busqueda'))
		document.getElementById('result_busqueda').innerHTML = '';
	if(document.getElementById('taula_puntuacions'))
		document.getElementById('taula_puntuacions').innerHTML = '';
	if( document.getElementById('grupo') ){
		if( (document.getElementById('grupo').value == 0) || (document.getElementById('num_jugadors').value == 0) ){
			document.getElementById('capa_cuadro_campos').style.display = 'none';
		}else if(document.getElementById('capa_cuadro_campos').style.display == 'none'){
			document.getElementById('capa_cuadro_campos').style.display = 'block';
		}
	}else
		document.getElementById('capa_cuadro_campos').style.display = 'none';
}

// funcio per amagar/mostrar els formularis d'introduir puntuacions individuals/grup
function actualitza_tipus_puntuacio(tipus){
	if(tipus == 'individual'){
		document.getElementById('sel_grupo').style.display = 'none';
		//document.getElementById('capa_select_jugadors').style.display = 'none';
		document.getElementById('capa_cuadro_campos').style.display = 'block';
		if(document.getElementById('result_busqueda'))
			document.getElementById('result_busqueda').innerHTML = '';
		if(document.getElementById('taula_puntuacions'))
			document.getElementById('taula_puntuacions').innerHTML = '';
		document.getElementById('tipus_puntuacio_actual').value = 'individual';
	}else if(tipus == 'grup'){
		document.getElementById('sel_grupo').style.display = 'block';
		//document.getElementById('capa_select_jugadors').style.display = 'block';
		comprova_selects_grup();
		if(document.getElementById('result_busqueda'))
			document.getElementById('result_busqueda').innerHTML = '';
		if(document.getElementById('taula_puntuacions'))
			document.getElementById('taula_puntuacions').innerHTML = '';
		document.getElementById('tipus_puntuacio_actual').value = 'grup';
	}
}

// funcio que actualitza la seleccio del listbox de jugadors en les puntuacions de grup
function actualitza_listbox_puntuacio( num_listbox, num_jugador){
	if(num_listbox == 1){
		if(document.getElementById('select2_jugador_'+num_jugador)){
			document.getElementById('select2_jugador_'+num_jugador).selectedIndex = document.getElementById('select1_jugador_'+num_jugador).selectedIndex;
		}
	}else if(num_listbox == 2){
		if(document.getElementById('select1_jugador_'+num_jugador)){
			document.getElementById('select1_jugador_'+num_jugador).selectedIndex = document.getElementById('select2_jugador_'+num_jugador).selectedIndex;
		}
	}
}


// funcio de paginacio del ultims resultats de la pagina de grup
function actualitza_resultats_grup(grup,pagina,total){
	var target = "capa_ultims_resultats";
	if( (grup != '') && (grup != undefined) && (grup != null)){
		var crida = "ajax-grup-resultats.php?target="+target+"&grup="+grup+"&pagina="+pagina+"&total="+total;
		cridaAJAX_resultats_camp(crida,1);
	}
}


function cridaAJAX_puntuacions(url){
	var httpRequest;
			
		var params="";

		try{
			params=url.split('?')[1];
			url=url.split('?')[0];
		}catch(e){}
		try{
			target=params.split('target=')[1].split('&')[0];
			//target=params.split('s=')[1];
			//target="";	
 		}catch(e){
			target="";	
		}
        if (window.XMLHttpRequest) { // Mozilla, Safari, ...
            httpRequest = new XMLHttpRequest();
            if (httpRequest.overrideMimeType) {
                httpRequest.overrideMimeType('text/xml');
            }
        } else if (window.ActiveXObject) { // IE
            try {
                httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
            }
        }

        if (!httpRequest) {
            alert(error_ajax);
            return false;
        }
        httpRequest.onreadystatechange = function() { 
			//posicionaCapaLoading();
			//mostraCapaLoading();
			camp_busq_callback_2(httpRequest,target); 
		};
        httpRequest.open('GET', url+"?"+params, true);
        httpRequest.send(null);
}

//muestra los resultados
function camp_busq_callback_2(httpRequest,target){
					
		 if (httpRequest.readyState == 4) {//la resposta un cop s'ha carregat
			//setTimeout(amagaCapaLoading,1000); 
			if (httpRequest.status == 200) {
				resposta=httpRequest.responseText;
				//alert(resposta);
				document.getElementById(target).innerHTML=resposta;
				//document.getElementById(target).style.display = "block";
			} else {
				alert(error_peticion);
			}
		}

}

// funcio per ordenar el ranking de grups
function ordenar_ranking(id_grup,camp,ordenacio){
	
	if((id_grup != null) && (camp != null) && (ordenacio != null)){
		//alert('grup='+id_grup+'&camp='+camp+'&ord='+ordenacio);
		FAjax_altres('ajax_ranking.php','taula_ranking','grup='+id_grup+'&camp='+camp+'&ord='+ordenacio,'post');
	}
}


// funcio per resetejar el cercador de puntuacions
function reset_buscador(){
	var id_jugador = document.getElementById('cerc_jug').value;
	document.buscador_puntuaciones.reset();
	/*
	if(document.getElementById('capa_resultados'))
		document.getElementById('capa_resultados').innerHTML = '<div class="paginacion"></div>';
	*/
	FAjax_cerca('ajax_cerca_puntuacions.php','capa_resultados','tasca=reset&j='+id_jugador,'post');
		
}

// funcio per cridar la cerca de puntuacions
function buscar_puntuaciones(){
	var id_jugador = document.getElementById('cerc_jug').value;
	var data_inici = document.getElementById('data_inici').value;
	var data_fi = document.getElementById('data_fi').value;
	var id_camp = document.getElementById('campo_buscador').value;
	var nom_camp = document.getElementById('campo_buscador').options[document.getElementById('campo_buscador').selectedIndex].text;
	
	if( (data_inici == '') || (data_fi == '')){
		alert(fechas_obligatorias);
	}else{
		if( id_jugador != null ){
			FAjax_cerca('ajax_cerca_puntuacions.php','capa_resultados','tasca=cerca&j='+id_jugador+'&data_inici='+data_inici+'&data_fi='+data_fi+'&c='+id_camp+'&nom='+nom_camp,'post');	
		}
	}
}

// funcio per resetejar el cercador de puntuacions
function reset_buscador_grup(){
	var id_grup = document.getElementById('cerc_grup').value;
	document.buscador_puntuaciones.reset();
	FAjax_cerca('ajax_cerca_puntuacions.php','capa_resultados','tasca=reset&g='+id_grup,'post');
		
}

// funcio per cridar la cerca de puntuacions de grup
function buscar_puntuaciones_grupo(){
	var id_grup = document.getElementById('cerc_grup').value;
	var data_inici = document.getElementById('data_inici').value;
	var data_fi = document.getElementById('data_fi').value;
	var id_camp = document.getElementById('campo_buscador').value;
	var nom_camp = document.getElementById('campo_buscador').options[document.getElementById('campo_buscador').selectedIndex].text;
	
	if( (data_inici == '') || (data_fi == '')){
		alert(fechas_obligatorias);
	}else{
		if( id_grup != null ){
			FAjax_cerca('ajax_cerca_puntuacions.php','capa_resultados','tasca=cerca&g='+id_grup+'&data_inici='+data_inici+'&data_fi='+data_fi+'&c='+id_camp+'&nom='+nom_camp,'post');	
		}
	}
}

// funcio per mostrar el formulari de pujar nova foto d'un camp
function mostra_form_fotos(){
	document.getElementById('taula_galeria').style.display = 'none';
	document.getElementById('capa_form_foto').style.display = 'block';
}

// funcio per amagar el formulari de pujar nova foto d'un camp
function amaga_form_fotos(){
	document.getElementById('capa_form_foto').style.display = 'none';
	document.getElementById('taula_galeria').style.display = 'block';
}

//funcio per esborrar una foto d'un torneig
function borrar_foto_torneo( id_foto, ruta ){
	if(confirm(confirm_borrar_foto_torneo)){
		if(id_foto != null && ruta != null){
			var torneo = document.getElementById('id_torneo').value;
			ajax_actiu = 1;
			
			FAjax('ajax-borrar-foto-torneo.php','galeria_torneo','foto='+id_foto+'&f='+ruta+'&t='+torneo,'post');
		}
	}
}

//funcio per esborrar una foto d'un torneig
function borrar_noticia_torneo( id_torneo, id_noticia ){
	if(confirm(confirm_borrar_noticia_torneo)){
		if(id_torneo != null && id_noticia != null){
			document.location.href = 'gestor-noticias.php?t='+id_torneo+'&e='+id_noticia;
		}
	}
}


// funcio de validacio del formulari de login dels organitzadors de tornejos (ANTIC)
function valida_login_organizador(form){
	var usuari = form.login_org.value;
	var clau = form.pwd_org.value;
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;   
	// mirem que no estiguin buits
	if( (usuari.length > 0) && (clau.length > 0) ){ 
		// comprovem el format
		if (reg.test(usuari)!=false) {
			form.action = "autentifica_organizador.php";
			form.submit();
		}else{
			alert(login_password_invalido);
		}
	}
}

// funcio de validacio del formulari de login dels organitzadors de tornejos
function valida_acceso_organizador(form){
	var usuari = form.login_org.value;
	var clau = form.pwd_org.value;
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;   
	// mirem que no estiguin buits
	if( (usuari.length > 0) && (clau.length > 0) ){ 
		// comprovem el format
		if (reg.test(usuari)!=false) {
			form.action = "autentifica-organizador.php";
			form.submit();
		}else{
			alert(login_password_invalido);
		}
	}
}

// funcio de validacio del formulari de login dels administradors de camps
function valida_acceso_administrador(form){
	var usuari = form.login_adm.value;
	var clau = form.pwd_adm.value;
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;   
	// mirem que no estiguin buits
	if( (usuari.length > 0) && (clau.length > 0) ){ 
		// comprovem el format
		if (reg.test(usuari)!=false) {
			form.action = "autentifica-administrador.php";
			form.submit();
		}else{
			alert(login_password_invalido);
		}
	}
}

// funcio que valida el formulari de generació de classificacions per tornejos i circuits
function valida_rankings(){
	var rankings_ok = true;
	
	if(document.getElementById('chk_scratch').checked){
		if(document.getElementById('chk_scratch1').checked){
			// scratch todo (no cal comprovar handicaps)
		}else if(document.getElementById('chk_scratch2').checked){
			// scratch masc/fem (no cal comprovar handicaps)
		}else{
			alert(alert_ranking_scratch);
			rankings_ok = false;
		}
	}
	
	if(document.getElementById('chk_indistinto').checked){
		if(document.getElementById('chk_indistinto2').checked){
			if(isNaN(document.getElementById("indistinto2_lim").value)){
				document.getElementById("indistinto2_lim").style.border = '1px solid red';
				alert(alert_handicap);
				rankings_ok = false;
			}else{
				var handicap = Number(document.getElementById("indistinto2_lim").value);
				document.getElementById("indistinto2_lim").value=handicap.toFixed(1);
				if(handicap>99 || handicap<=0.0){
					document.getElementById("indistinto2_lim").style.border = '1px solid red';
					alert(handicap_incorrecto);
					rankings_ok = false;
				}else{
					document.getElementById("indistinto2_lim").style.border = '';
				}
			}
		}else if(document.getElementById('chk_indistinto3').checked){
			if(isNaN(document.getElementById("indistinto3_lim1").value)){
				document.getElementById("indistinto3_lim1").style.border = '1px solid red';
				alert(alert_handicap);
				rankings_ok = false;
			}else{
				if(isNaN(document.getElementById("indistinto3_lim2").value)){
					document.getElementById("indistinto3_lim2").style.border = '1px solid red';
					alert(alert_handicap);
					rankings_ok = false;
				}else{
					var handicap = Number(document.getElementById("indistinto3_lim1").value);
					document.getElementById("indistinto3_lim1").value=handicap.toFixed(1);
					if(handicap>99 || handicap<=0.0){
						document.getElementById("indistinto3_lim1").style.border = '1px solid red';
						alert(handicap_incorrecto);
						rankings_ok = false;
					}else{
						document.getElementById("indistinto3_lim1").style.border = '';
						var handicap = Number(document.getElementById("indistinto3_lim2").value);
						document.getElementById("indistinto3_lim2").value=handicap.toFixed(1);
						if(handicap>99 || handicap<=0.0){
							document.getElementById("indistinto3_lim2").style.border = '1px solid red';
							alert(handicap_incorrecto);
							rankings_ok = false;
						}else{
							document.getElementById("indistinto3_lim2").style.border = '';
						}
					}
				}
			}
		}else if(document.getElementById('chk_indistinto4').checked){
			if(isNaN(document.getElementById("indistinto4_lim1").value)){
				document.getElementById("indistinto4_lim1").style.border = '1px solid red';
				alert(alert_handicap);
				rankings_ok = false;
			}else{
				if(isNaN(document.getElementById("indistinto4_lim2").value)){
					document.getElementById("indistinto4_lim2").style.border = '1px solid red';
					alert(alert_handicap);
					rankings_ok = false;
				}else{
					if(isNaN(document.getElementById("indistinto4_lim3").value)){
						document.getElementById("indistinto4_lim3").style.border = '1px solid red';
						alert(alert_handicap);
						rankings_ok = false;
					}else{
						var handicap = Number(document.getElementById("indistinto4_lim1").value);
						document.getElementById("indistinto4_lim1").value=handicap.toFixed(1);
						if(handicap>99 || handicap<=0.0){
							document.getElementById("indistinto4_lim1").style.border = '1px solid red';
							alert(handicap_incorrecto);
							rankings_ok = false;
						}else{
							document.getElementById("indistinto4_lim1").style.border = '';
							var handicap = Number(document.getElementById("indistinto4_lim2").value);
							document.getElementById("indistinto4_lim2").value=handicap.toFixed(1);
							if(handicap>99 || handicap<=0.0){
								document.getElementById("indistinto4_lim2").style.border = '1px solid red';
								alert(handicap_incorrecto);
								rankings_ok = false;
							}else{
								document.getElementById("indistinto4_lim2").style.border = '';
								var handicap = Number(document.getElementById("indistinto4_lim3").value);
								document.getElementById("indistinto4_lim3").value=handicap.toFixed(1);
								if(handicap>99 || handicap<=0.0){
									document.getElementById("indistinto4_lim3").style.border = '1px solid red';
									alert(handicap_incorrecto);
									rankings_ok = false;
								}else{
									document.getElementById("indistinto4_lim3").style.border = '';
								}
							}
						}
					}
				}
			}
			
		}else{
			alert(alert_ranking_indistinto);
			rankings_ok = false;
		}
	}
	
	if(document.getElementById('chk_masc').checked){
		if(document.getElementById('chk_masc2').checked){
			if(isNaN(document.getElementById("masc2_lim").value)){
				document.getElementById("masc2_lim").style.border = '1px solid red';
				alert(alert_handicap);
				rankings_ok = false;
			}else{
				var handicap = Number(document.getElementById("masc2_lim").value);
				document.getElementById("masc2_lim").value=handicap.toFixed(1);
				if(handicap>99 || handicap<=0.0){
					document.getElementById("masc2_lim").style.border = '1px solid red';
					alert(handicap_incorrecto);
					rankings_ok = false;
				}else{
					document.getElementById("masc2_lim").style.border = '';
				}
			}
		}else if(document.getElementById('chk_masc3').checked){
			if(isNaN(document.getElementById("masc3_lim1").value)){
				document.getElementById("masc3_lim1").style.border = '1px solid red';
				alert(alert_handicap);
				rankings_ok = false;
			}else{
				if(isNaN(document.getElementById("masc3_lim2").value)){
					document.getElementById("masc3_lim2").style.border = '1px solid red';
					alert(alert_handicap);
					rankings_ok = false;
				}else{
					var handicap = Number(document.getElementById("masc3_lim1").value);
					document.getElementById("masc3_lim1").value=handicap.toFixed(1);
					if(handicap>99 || handicap<=0.0){
						document.getElementById("masc3_lim1").style.border = '1px solid red';
						alert(handicap_incorrecto);
						rankings_ok = false;
					}else{
						document.getElementById("masc3_lim1").style.border = '';
						var handicap = Number(document.getElementById("masc3_lim2").value);
						document.getElementById("masc3_lim2").value=handicap.toFixed(1);
						if(handicap>99 || handicap<=0.0){
							document.getElementById("masc3_lim2").style.border = '1px solid red';
							alert(handicap_incorrecto);
							rankings_ok = false;
						}else{
							document.getElementById("masc3_lim2").style.border = '';
						}
					}
				}
			}
		}else if(document.getElementById('chk_masc4').checked){
			if(isNaN(document.getElementById("masc4_lim1").value)){
				document.getElementById("masc4_lim1").style.border = '1px solid red';
				alert(alert_handicap);
				rankings_ok = false;
			}else{
				if(isNaN(document.getElementById("masc4_lim2").value)){
					document.getElementById("masc4_lim2").style.border = '1px solid red';
					alert(alert_handicap);
					rankings_ok = false;
				}else{
					if(isNaN(document.getElementById("masc4_lim3").value)){
						document.getElementById("masc4_lim3").style.border = '1px solid red';
						alert(alert_handicap);
						rankings_ok = false;
					}else{
						var handicap = Number(document.getElementById("masc4_lim1").value);
						document.getElementById("masc4_lim1").value=handicap.toFixed(1);
						if(handicap>99 || handicap<=0.0){
							document.getElementById("masc4_lim1").style.border = '1px solid red';
							alert(handicap_incorrecto);
							rankings_ok = false;
						}else{
							document.getElementById("masc4_lim1").style.border = '';
							var handicap = Number(document.getElementById("masc4_lim2").value);
							document.getElementById("masc4_lim2").value=handicap.toFixed(1);
							if(handicap>99 || handicap<=0.0){
								document.getElementById("masc4_lim2").style.border = '1px solid red';
								alert(handicap_incorrecto);
								rankings_ok = false;
							}else{
								document.getElementById("masc4_lim2").style.border = '';
								var handicap = Number(document.getElementById("masc4_lim3").value);
								document.getElementById("masc4_lim3").value=handicap.toFixed(1);
								if(handicap>99 || handicap<=0.0){
									document.getElementById("masc4_lim3").style.border = '1px solid red';
									alert(handicap_incorrecto);
									rankings_ok = false;
								}else{
									document.getElementById("masc4_lim3").style.border = '';
								}
							}
						}
					}
				}
			}
		}else{
			alert(alert_ranking_caballeros);
			rankings_ok = false;
		}
	}
	
	if(document.getElementById('chk_fem').checked){
		if(document.getElementById('chk_fem1').checked){
			// damas todo (no cal comprovar handicaps)
		}else if(document.getElementById('chk_fem2').checked){
			if(isNaN(document.getElementById("fem2_lim").value)){
				document.getElementById("fem2_lim").style.border = '1px solid red';
				alert(alert_handicap);
				rankings_ok = false;
			}else{
				var handicap = Number(document.getElementById("fem2_lim").value);
				document.getElementById("fem2_lim").value=handicap.toFixed(1);
				if(handicap>99 || handicap<=0.0){
					document.getElementById("fem2_lim").style.border = '1px solid red';
					alert(handicap_incorrecto);
					rankings_ok = false;
				}else{
					document.getElementById("fem2_lim").style.border = '';
				}
			}
		}else{
			alert(alert_ranking_damas);
			rankings_ok = false;
		}
	}
	
	return rankings_ok;
}

// funcio per validar el formulari d'edicio de puntuacions d'un torneig
function valida_torneo_puntuaciones(){
	var num = 1;
	var tot_ok = true;
	while($('#fila'+num).length > 0){
		// nomes els que tinguin check marcat
		if($('#p'+num+'_check').is(':checked')){
			//obligatori llicencia,hex i hj; els forats buits es permeten
			
			// si es una puntuacio nova (tindra el flag de NEW), comprovem la llicencia
			if(document.getElementById('p'+num+'_new')){
				//llicencia
				if(document.getElementById('p'+num+'_llic').value.length == 10){
					// valor ok
					$('#p'+num+'_llic').removeClass('input_error');
				}else{ // valor erroni
					$('#p'+num+'_llic').addClass('input_error');
					tot_ok=false;
				}
			}
			// hcp exacte
			if(document.getElementById('p'+num+'_hex').value.length > 0 && !isNaN(document.getElementById('p'+num+'_hex').value)){
				var hex = Number($('#p'+num+'_hex').val());
				$('#p'+num+'_hex').val(hex.toFixed(1));
				if(hex>99 || hex<-10){ // valor invalid
					$('#p'+num+'_hex').addClass('input_error');
					tot_ok=false;
				}else{ // valor ok
					$('#p'+num+'_hex').removeClass('input_error');
				}
			}else{ // esta buit
				$('#p'+num+'_hex').addClass('input_error');
				tot_ok=false;
			}
			// hcp de joc
			if(document.getElementById('p'+num+'_hj').value.length > 0 && !isNaN(document.getElementById('p'+num+'_hj').value)){
				var hk = Number($('#p'+num+'_hj').val());
				//$('#p'+num+'_hj').val(hk.toFixed(1));
				if(hk>99 || hk<-10){ // valor invalid
					$('#p'+num+'_hj').addClass('input_error');
					tot_ok=false;
				}else{ // valor ok
					$('#p'+num+'_hj').removeClass('input_error');
				}
			}else{ // esta buit
				$('#p'+num+'_hj').addClass('input_error');
				tot_ok=false;
			}
		}
		
		num++;
		if(num > 1000) break;
	}
	if(tot_ok){
		// comprovem que no hi hagi cap llicencia repetida
		for(j=1;j<num;j++){
			for(k=1;k<num;k++){
				if(j != k){
					if(document.getElementById('p'+j+'_llic').value == document.getElementById('p'+k+'_llic').value){
						$('#p'+k+'_llic').addClass('input_error');
						tot_ok=false;
					}
				}
			}
		}
		if(tot_ok){
			for(j=1;j<num;j++){
				$('#p'+j+'_llic').removeClass('input_error');
			}
			document.form_editar_puntuaciones.action = 'bd-torneo-editar-puntuaciones.php';
			document.form_editar_puntuaciones.submit();
			//alert('OK');
		}else{
			alert(alert_licencias_repetidas);
		}
	}else{
		alert(avis_puntuacio_invalida);
	}
}

// funcio per afegir una nova fila al formulari d'edicio de puntuacions d'un torneig
function afegir_puntuacio_torneig(){
	var proper_id = parseInt(document.getElementById('next_player').value);
	if (window.ActiveXObject) { // IE
		// ho hem de fer amb divs
		var new_row = document.createElement('div');
		new_row.setAttribute('id','fila'+proper_id);
		new_row.setAttribute('className','fila'); // IE7
		new_row.setAttribute('class','fila');
		document.getElementById('inner_table').appendChild(new_row);
		
		var crida="ajax-add-score-ie.php?target=fila"+proper_id+"&n="+proper_id;
		
	}else{
		// afegim una <tr>
		var new_row = document.createElement('tr');
		new_row.setAttribute('id','fila'+proper_id);
		document.getElementById('table_edit_scores').appendChild(new_row);
	
		var crida="ajax-add-score.php?target=fila"+proper_id+"&n="+proper_id;
	}
	cridaAJAX_cerca(crida);
	document.getElementById('next_player').value = proper_id+1;
	if(proper_id == 1 && document.getElementById('no_results')) document.getElementById('no_results').style.display = 'none';
}

// funcio per esborrar les puntuacions seleccionades d'un torneig
function borrar_torneo_puntuaciones(){
	var num = 1;
	var tot_ok = false;
	while($('#p'+num+'_check').length > 0){
		if($('#p'+num+'_check').is(':checked')){
			tot_ok = true;
			break;
		}
		num++;
		if(num > 1000) break;
	}
	if(tot_ok){
		if(confirm(avis_esborrar_puntuacio)){
			document.form_editar_puntuaciones.action = 'bd-torneo-borrar-puntuaciones.php';
			document.form_editar_puntuaciones.submit();
		}
	}
}

// funcio per marcar/desmarcar totes les puntuacions de l'editor de resultats d'un torneig
function toggle_fila_all(){
	var num = 1;
	if($('#all_check').is(':checked')){ // marcar tots
		while($('#fila'+num).length > 0){
			$('#p'+num+'_check').attr('checked', true);
			$('#fila'+num).addClass('fila_drop');
			num++;
			if(num > 1000) break;
		}
	}else{ // desmarcar tots
		while($('#fila'+num).length > 0){
			$('#p'+num+'_check').attr('checked', false);
			$('#fila'+num).removeClass('fila_drop');
			num++;
			if(num > 1000) break;
		}
	}
}

// funcio per validar el formulari d'edicio de puntuacions d'un torneig PROAM
function valida_torneo_proam_puntuaciones(){
	var num = 1;
	var tot_ok = true;
	while($('#fila'+num).length > 0){
		//obligatori els 4 noms, tee i hj; els forats buits es permeten
		
		// nom pro
		if(document.getElementById('p'+num+'_pro').value.length > 0){
			$('#p'+num+'_pro').removeClass('input_error');
		}else{
			$('#p'+num+'_pro').addClass('input_error');
			tot_ok=false;
		}
		// nom amateurs
		for(am=1;am<=3;am++){
			if(document.getElementById('p'+num+'_am'+am).value.length > 0){
				$('#p'+num+'_am'+am).removeClass('input_error');
			}else{
				$('#p'+num+'_am'+am).addClass('input_error');
				tot_ok=false;
			}
		}
		// hora
		hora_pattern = /^([0-1][0-9]|[2][0-3]):([0-5][0-9])$/;
		if(document.getElementById('p'+num+'_hora').value.length > 0){
			if( !hora_pattern.test(document.getElementById('p'+num+'_hora').value)){
				$('#p'+num+'_hora').addClass('input_error');
				tot_ok=false;
			}else{
				$('#p'+num+'_hora').removeClass('input_error');
			}
		}else{ // esta buit
			$('#p'+num+'_hora').removeClass('input_error');
		}           
		// tee (num entre 1 i 18)
		if(document.getElementById('p'+num+'_tee').value.length > 0 && !isNaN(document.getElementById('p'+num+'_tee').value)){
			var tee = Number($('#p'+num+'_tee').val());
			if(tee>18 || tee<1){ // valor invalid
				$('#p'+num+'_tee').addClass('input_error');
				tot_ok=false;
			}else{ // valor ok
				$('#p'+num+'_tee').removeClass('input_error');
			}
		}else{ // esta buit
			$('#p'+num+'_tee').addClass('input_error');
			tot_ok=false;
		}			
		// hcp exacte (que sigui num)
		if(document.getElementById('p'+num+'_hex').value.length > 0 && !isNaN(document.getElementById('p'+num+'_hex').value)){
			var hex = Number($('#p'+num+'_hex').val());
			$('#p'+num+'_hex').val(hex.toFixed(1));
			if(hex>99 || hex<-10){ // valor invalid
				$('#p'+num+'_hex').addClass('input_error');
				tot_ok=false;
			}else{ // valor ok
				$('#p'+num+'_hex').removeClass('input_error');
			}
		}else{ // esta buit
			$('#p'+num+'_hex').removeClass('input_error');
		}
		// hcp de joc
		if(document.getElementById('p'+num+'_hj').value.length > 0 && !isNaN(document.getElementById('p'+num+'_hj').value)){
			var hk = Number($('#p'+num+'_hj').val());
			//$('#p'+num+'_hj').val(hk.toFixed(1));
			if(hk>99 || hk<-10){ // valor invalid
				$('#p'+num+'_hj').addClass('input_error');
				tot_ok=false;
			}else{ // valor ok
				$('#p'+num+'_hj').removeClass('input_error');
			}
		}else{ // esta buit
			$('#p'+num+'_hj').addClass('input_error');
			tot_ok=false;
		}
		
		num++;
		if(num > 1000) break;
	}
	if(tot_ok){
		document.form_editar_puntuaciones.action = 'bd-torneo-proam-editar-puntuaciones.php';
		document.form_editar_puntuaciones.submit();
		//alert('OK');
	}else{
		alert(avis_puntuacio_proam_invalida);
	}
}

// funcio per afegir una nova fila al formulari d'edicio de puntuacions d'un torneig PROAM
function afegir_puntuacio_torneig_proam(){
	var proper_id = parseInt(document.getElementById('next_player').value);
	var new_row = document.createElement('div');
	new_row.setAttribute('id','fila'+proper_id);
	new_row.setAttribute('className','fila'); // IE7
	new_row.setAttribute('class','fila');
	document.getElementById('proam_table').appendChild(new_row);
		
	var crida="ajax-add-team.php?target=fila"+proper_id+"&n="+proper_id;
	cridaAJAX_cerca(crida);
	document.getElementById('next_player').value = proper_id+1;
}

// funcio per esborrar les puntuacions seleccionades d'un torneig PROAM
function borrar_torneo_proam_puntuaciones(){
	var num = 1;
	var tot_ok = false;
	while($('#p'+num+'_check').length > 0){
		if($('#p'+num+'_check').is(':checked')){
			tot_ok = true;
			break;
		}
		num++;
		if(num > 1000) break;
	}
	if(tot_ok){
		if(confirm(avis_esborrar_puntuacio)){
			document.form_editar_puntuaciones.action = 'bd-torneo-proam-borrar-puntuaciones.php';
			document.form_editar_puntuaciones.submit();
		}
	}
}

// funcio per enviar el form d'actualitzar la visibilitat dels resultats d'un torneig
function actualitza_visibilitat(){
	document.form_torneo.action = "bd-torneo-visible.php";
	document.form_torneo.submit();
}

// funcio per validar el formulari d'editar torneig (ANTIC)
function valida_torneo(){
	if(document.getElementById('tee').value != 0){
		document.getElementById('descripcio').value = ReplaceEnters(document.getElementById('descripcio').value, true);
		document.form_torneo.submit();
	}else{
		alert(error_falta_tee);	
	}
}

// funcio per validar el formulari de crear nou torneig
function valida_nuevo_torneo(){
	if(document.getElementById('nom').value.length > 2){
		if(document.getElementById('id_camp').value != 0){
			if(document.getElementById('tee') && document.getElementById('tee').value != 0){
				if(document.getElementById('data_inici').value.length == 10){
					if(document.getElementById('id_modalitat') && document.getElementById('id_modalitat').value != 0){
						document.getElementById('descripcio').value = ReplaceEnters(document.getElementById('descripcio').value, true);
						document.form_nuevo_torneo.submit();
					}else{
						alert(error_falta_camp_basic);	
					}
				}else{
					alert(error_falta_camp_basic);	
				}
			}else{
				alert(error_falta_camp_basic);	
			}
		}else{
			alert(error_falta_camp_basic);	
		}
	}else{
		alert(error_falta_camp_basic);	
	}
}

// funcio per validar el formulari d'editar torneig
function valida_edit_torneo(){
	if(document.getElementById('nom').value.length > 2){
		if(document.getElementById('tee') && document.getElementById('tee').value != 0){
			if(document.getElementById('data_inici').value.length == 10){
				if(document.getElementById('id_modalitat') && document.getElementById('id_modalitat').value != 0){
					
					// validem el nou apartat Rankings a generar
					var rankings_ok = true;
					rankings_ok = valida_rankings();
							
					if(rankings_ok){
						document.getElementById('descripcio').value = ReplaceEnters(document.getElementById('descripcio').value, true);
						//alert('ok');
						document.form_edit_torneo.submit();
					}
				}else{
					alert(error_falta_camp_basic);	
				}
			}else{
				alert(fecha_invalida);	
			}
		}else{
			alert(error_falta_tee);	
		}
	}else{
		alert(nombre_obligatorio);	
	}
}

// funcio per redirigir a la pagina d'editar torneig
function editar_torneo(id){
	if(id != null){
		document.location.href="editar_torneo.php?t="+id;
	}
}

// funcio per validar el formulari d'editar una volta (torneig simple dins un torneig multivolta)
function valida_edit_vuelta(){
	if(document.getElementById('nom').value.length > 2){
		if(document.getElementById('tee') && document.getElementById('tee').value != 0){
			// validem el nou apartat Rankings a generar
			var rankings_ok = true;
			rankings_ok = valida_rankings();
					
			if(rankings_ok){
				document.getElementById('descripcio').value = ReplaceEnters(document.getElementById('descripcio').value, true);
				//alert('ok');
				document.form_edit_torneo.submit();
			}
		}else{
			alert(error_falta_tee);	
		}
	}else{
		alert(nombre_obligatorio);	
	}
}

function actualitza_label_hcp(event,id_input){
	var resposta = acceptNumDecimals_only(event);
	if(resposta){
		if(document.getElementById(id_input+"_dis")){
			document.getElementById(id_input+"_dis").value = document.getElementById(id_input).value;
		}
	}else{
		document.getElementById(id_input).value = document.getElementById(id_input+"_dis").value;
	}
	return resposta;
}

// funcio per marcar/desmarcar una fila de puntuacio a l'editor de puntuacions
function toggle_fila(num_fila){
	if($('#p'+num_fila+'_check').attr('checked')) $('#fila'+num_fila).addClass('fila_drop');
	else $('#fila'+num_fila).removeClass('fila_drop');
}

// funcio per ordenar el llistat de mistorneos.php
function ordenar_torneos(camp,ordenacio){
	if((camp != null) && (ordenacio != null)){
		FAjax_altres('ajax_mistorneos.php','taula_tornejos','camp='+camp+'&ord='+ordenacio,'post');
	}
}

// funcio per ordenar el llistat de torneos.php
function ordenar_ultimos_torneos(camp,ordenacio){
	if((camp != null) && (ordenacio != null)){
		FAjax_altres('ajax_ultimos_torneos.php','taula_tornejos','camp='+camp+'&ord='+ordenacio,'post');
	}
}

//funcio per actualitzar el ranking d'un torneig al mode detallat
function ranking_detalles(id){
	if(id != null){
		var id_circuit = 0;
		if(document.getElementById('hid_circuito')) id_circuit = document.getElementById('hid_circuito').value;
		FAjax_altres('ajax_torneo_ranking_detalles.php','taula_ranking','t='+id+'&cir='+id_circuit,'post');
	}
}

//funcio per actualitzar la categoria del ranking d'un torneig
function ranking_totales(id,categoria,limit_masc,limit_fem){
	if(id != null){
		if(limit_masc == null || limit_masc == -1){
			limit_masc = '';
		}
		if(limit_fem == null){
			limit_fem = '';
		}
		var id_circuit = 0;
		if(document.getElementById('hid_circuito')) id_circuit = document.getElementById('hid_circuito').value;
		FAjax_altres('ajax_torneo_ranking_totales.php','taula_ranking','t='+id+'&c='+categoria+'&lim_m='+limit_masc+'&lim_f='+limit_fem+'&cir='+id_circuit+'&flag_e='+document.getElementById('hid_flag_excloure').value,'post');
	}
}

//funcio per actualitzar el ranking d'un torneig al mode classificacio SCRATCH
function ranking_scratch(id,cat){
	if(id != null){
		var id_circuit = 0;
		var categoria = 6; // scratch indistinto
		if(cat != null) categoria = cat;
		if(document.getElementById('hid_circuito')) id_circuit = document.getElementById('hid_circuito').value;
		FAjax_altres('ajax_torneo_ranking_scratch.php','taula_ranking','t='+id+'&cir='+id_circuit+'&cat='+categoria+'&flag_e='+document.getElementById('hid_flag_excloure').value,'post');
	}
}
//funcio per actualitzar el ranking d'un torneig STABLEFORD al mode classificacio SCRATCH
function ranking_scratch_stableford(id,cat){
	if(id != null){
		var id_circuit = 0;
		var categoria = 6; // scratch indistinto
		if(cat != null) categoria = cat;
		if(document.getElementById('hid_circuito')) id_circuit = document.getElementById('hid_circuito').value;
		FAjax_altres('ajax_torneo_ranking_scratch_stableford.php','taula_ranking','t='+id+'&cir='+id_circuit+'&cat='+categoria+'&flag_e='+document.getElementById('hid_flag_excloure').value,'post');
	}
}

//funcio per actualitzar el ranking d'un torneig al mode punts (GECKO)
function ranking_puntos(id){
	if(id != null){
		var id_circuit = 0;
		if(document.getElementById('hid_circuito')) id_circuit = document.getElementById('hid_circuito').value;
		FAjax_altres('ajax_torneo_ranking_puntos.php','taula_ranking','t='+id+'&cir='+id_circuit,'post');
	}
}

//funcio per actualitzar la categoria del ranking d'un circuit
function ranking_totales_circuito(id,categoria,limit_masc,limit_fem){
	if(id != null){
		if(limit_masc == null || limit_masc == -1){
			// no tenim limit de hcp, mostrem tots els jugadors
			limit_masc = '';
		}
		if(limit_fem == null){
			// no tenim limit de hcp femeni, mostrem totes les jugadores
			limit_fem = '';
		}
		var modalitat = document.getElementById('hid_modalitat').value;
		var params_eclectic = '';
		if(modalitat == 5){ // Eclectic Stableford
			for(var f=1;f<=18;f++){
				params_eclectic += '&p'+f+'='+document.getElementById('p'+f).value;
				params_eclectic += '&h'+f+'='+document.getElementById('h'+f).value;
				params_eclectic += '&h'+f+'_fem='+document.getElementById('h'+f+'_fem').value;
			}
		}
		FAjax_altres('ajax-circuito-ranking-totales.php','taula_ranking','cir='+id+'&c='+categoria+'&lim_m='+limit_masc+'&lim_f='+limit_fem+'&mod='+modalitat+'&tip='+document.getElementById('hid_tipus').value+'&reg='+document.getElementById('hid_reglament').value+'&pen='+document.getElementById('hid_penalitzacio').value+'&hcp='+document.getElementById('hid_handicap').value+'&num='+document.getElementById('hid_num_targetes').value+'&min='+document.getElementById('hid_min_targetes').value+'&flag_m='+document.getElementById('hid_flag_multivolta').value+'&flag_e='+document.getElementById('hid_flag_excloure').value+params_eclectic,'post');
	}
}
//funcio per actualitzar el ranking d'un circuit al mode classificacio SCRATCH
function ranking_scratch_circuito(id,cat){
	if(id != null){
		var categoria = 6; // scratch indistinto
		if(cat != null) categoria = cat;
		var modalitat = document.getElementById('hid_modalitat').value;
		var params_eclectic = '';
		if(modalitat == 5){ // Eclectic Stableford
			for(var f=1;f<=18;f++){
				params_eclectic += '&p'+f+'='+document.getElementById('p'+f).value;
				params_eclectic += '&h'+f+'='+document.getElementById('h'+f).value;
				params_eclectic += '&h'+f+'_fem='+document.getElementById('h'+f+'_fem').value;
			}
		}
		FAjax_altres('ajax-circuito-ranking-scratch.php','taula_ranking','cir='+id+'&mod='+modalitat+'&tip='+document.getElementById('hid_tipus').value+'&reg='+document.getElementById('hid_reglament').value+'&pen='+document.getElementById('hid_penalitzacio').value+'&hcp='+document.getElementById('hid_handicap').value+'&flag_m='+document.getElementById('hid_flag_multivolta').value+'&flag_e='+document.getElementById('hid_flag_excloure').value+'&num='+document.getElementById('hid_num_targetes').value+'&min='+document.getElementById('hid_min_targetes').value+'&cat='+categoria+params_eclectic,'post');
	}
}

//funcio per carregar el ranking preliminar d'un circuit
function ranking_totales_circuito_preliminar(id,categoria,limit_masc,limit_fem){
	if(id != null){
		if(limit_masc == null || limit_masc == -1){
			// no tenim limit de hcp, mostrem tots els jugadors
			limit_masc = '';
		}
		if(limit_fem == null){
			// no tenim limit de hcp femeni, mostrem totes les jugadores
			limit_fem = '';
		}
		
		FAjax_altres('ajax-circuito-ranking-totales.php','ranking_preliminar','cir='+id+'&c='+categoria+'&lim_m='+limit_masc+'&lim_f='+limit_fem+'&mod='+document.getElementById('hid_modalitat').value+'&tip='+document.getElementById('hid_tipus').value+'&reg='+document.getElementById('hid_reglament').value+'&pen='+document.getElementById('hid_penalitzacio').value+'&hcp='+document.getElementById('hid_handicap').value+'&num='+document.getElementById('hid_num_targetes').value+'&min='+document.getElementById('hid_min_targetes').value+'&flag_m='+document.getElementById('hid_flag_multivolta').value+'&flag_e='+document.getElementById('hid_flag_excloure').value+'&preliminar=true','post');
	}
}

//funcio per actualitzar la categoria del ranking d'un torneig multivolta
function ranking_totales_multi(id,categoria){
	if(id != null){
		var id_circuit = 0;
		if(document.getElementById('hid_circuito')) id_circuit = document.getElementById('hid_circuito').value;
		FAjax_altres('ajax-multitorneo-ranking-totales.php','taula_ranking','multi='+id+'&c='+categoria+'&mod='+document.getElementById('hid_modalitat').value+'&tip='+document.getElementById('hid_tipus').value+'&num='+document.getElementById('hid_num_voltes').value+'&cir='+id_circuit,'post');
	}
}

//funcio de validacio del formulari de pujar excel de mipuntuacion del torneig
function validar_excel(){
	if(document.getElementById('excel').value.length > 0){
		document.form_torneo.action = "excel-confirm.php";
		document.form_torneo.submit();
	}else{
		alert(excel_torneo_vacio);
	}
}

//funcio de validacio del formulari de pujar excel "oficial" del torneig
function validar_excel_oficial(){
	if(document.getElementById('excel_oficial').value.length > 0){
		document.form_torneo.action = "excel_oficial-confirm.php";
		document.form_torneo.submit();
	}else{
		alert(excel_torneo_vacio);
	}
}

//funcio de validacio del formulari de pujar fitxer txt en format compuwin de resultats del torneig
function validar_compuwin(){
	if(document.getElementById('compuwin').value.length > 0){
		document.form_torneo.action = "compuwin-confirm.php";
		document.form_torneo.submit();
	}else{
		alert(compuwin_torneo_vacio);
	}
}

//funcio de validacio del formulari de pujar fitxer res en format compwin2 de resultats del torneig
function validar_compwin2(){
	if(document.getElementById('compwin2').value.length > 0){
		document.form_torneo.action = "compwin2-confirm.php";
		document.form_torneo.submit();
	}else{
		alert(compwin2_torneo_vacio);
	}
}

//funcio de validacio del formulari de pujar fitxer en format flashcaddy de resultats del torneig
function validar_flashcaddy(){
	if(document.getElementById('flashcaddy').value.length > 0){
		document.form_torneo.action = "flashcaddy-confirm.php";
		document.form_torneo.submit();
	}else{
		alert(flashcaddy_torneo_vacio);
	}
}

//funcio per esborrar l'excel temporal d'un torneig
function cancelar_excel(id){
	if(id != null){
		document.location.href="esborrar_excel.php?t="+id;
	}
}

//funcio per esborrar el fitxer de resultats compuwin temporal d'un torneig
function cancelar_compuwin(id){
	if(id != null){
		document.location.href="esborrar_compuwin.php?t="+id;
	}
}

//funcio per esborrar el fitxer de resultats compuwin temporal d'un torneig
function cancelar_compwin2(id){
	if(id != null){
		document.location.href="esborrar_compwin2.php?t="+id;
	}
}


// funcio per validar el formulari de crear nou circuit
function valida_nuevo_circuito(){
	if(document.getElementById('nom').value.length > 2){
		if(document.getElementById('tipus_golf').checked == true || document.getElementById('tipus_pp').checked == true){
			if((document.getElementById('id_modalitat') && document.getElementById('id_modalitat').value != 0) || (!document.getElementById('id_modalitat'))){
				if(document.getElementById("id_reglament_ranking") && document.getElementById("id_reglament_ranking").value > 0 ){
					if(document.getElementById("fila_num_targetes").style.display=='none' || (!isNaN(document.getElementById("num_millors_targetes").value) && document.getElementById("num_millors_targetes").value > 0) ){
						
						document.getElementById('reglament').value = ReplaceEnters(document.getElementById('reglament').value, true);
						document.form_nuevo_circuito.submit();
					}else{
						alert(alert_numerico);	
					}
				}else{
					alert(error_falta_camp_basic);	
				}
			}else{
				alert(error_falta_camp_basic);	
			}
		}else{
			alert(error_falta_camp_basic);	
		}
	}else{
		alert(error_falta_camp_basic);	
	}
}

// funcio per validar el formulari d'editar circuit
function valida_edit_circuito(){
	if(document.getElementById('nom').value.length > 2){
		if(document.getElementById('tipus_golf').checked == true || document.getElementById('tipus_pp').checked == true){
			if((document.getElementById('id_modalitat') && document.getElementById('id_modalitat').value != 0) || (!document.getElementById('id_modalitat'))){
				if(document.getElementById("id_reglament_ranking") && document.getElementById("id_reglament_ranking").value > 0 ){
					if(document.getElementById("fila_num_targetes").style.display=='none' || (!isNaN(document.getElementById("num_millors_targetes").value) && document.getElementById("num_millors_targetes").value > 0) ){
						
						// validem el nou apartat Rankings a generar
						var rankings_ok = true;
						rankings_ok = valida_rankings();
								
						if(rankings_ok){
							document.getElementById('reglament').value = ReplaceEnters(document.getElementById('reglament').value, true);
							document.form_nuevo_circuito.submit();
						}
						
					}else{
						alert(alert_numerico);	
					}
				}else{
					alert(error_falta_camp_basic);	
				}
			}else{
				alert(error_falta_camp_basic);	
			}
		}else{
			alert(error_falta_camp_basic);	
		}
	}else{
		alert(error_falta_camp_basic);	
	}
}

					
//funcio per demanar el codi d'un producte
function mostra_codi(id){
	if(id != null){
		FAjax_promocions('ajax-bono.php','capa_codigo_'+id,'id='+id,'post');
		document.getElementById('capa_codigo_'+id).className = 'mi_codigo';
		//document.getElementById('capa_ver_codigo_'+id).innerHTML = '';
	}
}

//funcio per incrementar el comptador de clics d'un producte en promocio
function incrementa_clics(id){
	if(id != null){
		FAjax_clics('ajax-clics-producte.php','id='+id);
	}
}


/*** NOVES PUNTUACIONS DETALLADES **/
function updateGIR(forat) {
	var par;
	var cops;
	var putts;
	var i = 1;
	
 	if( document.getElementById('putts').checked == false ) {
		for(i=1;i<=18;i++) {
			if(document.getElementById('green'+i)){
				document.getElementById('green'+i).innerHTML = "-";
				document.getElementById('gir'+i).value = 0;
			}
		}
		if(document.getElementById('girs_1_9')) document.getElementById('girs_1_9').style.visibility = 'hidden';
		if(document.getElementById('girs_10_18')) document.getElementById('girs_10_18').style.visibility = 'hidden';
	} else {
		par = document.getElementById('par'+forat).innerHTML;
		cops = document.getElementById('golpe'+forat).value;
		putts = document.getElementById('putt'+forat).value;
		//alert(par);
		
		if( (!isNaN(par)) && (cops != "") && (putts != "") ) {
			if( (cops - putts) > 0 ){
				if( cops - putts <= par - 2) {
					document.getElementById('green'+forat).innerHTML = '<img src="img/tick.png" alt="'+gir_si+'" title="'+gir_si+'" height="14" />';
					document.getElementById('gir'+forat).value = '1';
				} else {
					document.getElementById('green'+forat).innerHTML = '<img src="img/untick.png" alt="'+gir_no+'" title="'+gir_no+'" height="14" />';
					document.getElementById('gir'+forat).value = '0';
				}
			}else{
				document.getElementById('green'+forat).innerHTML = "-";
				document.getElementById('gir'+forat).value = '0';
				alert(error_putt);
				document.getElementById('putt'+forat).value = "";
			}
		} else {
			document.getElementById('green'+forat).innerHTML = "-";
			document.getElementById('gir'+forat).value = '0';
		}
		
 	}
}

function updateGIR_grupo(id) {
	var par;
	var cops;
	var putts;
	var i = 1;
	var str_id = id.split('_');
	var forat = str_id[0];
	var jugador = str_id[1];
	
 	if( document.getElementById('putts').checked == false ) {
		for(i=1;i<=18;i++) {
			if(document.getElementById('green'+i+'_'+jugador)){
				document.getElementById('green'+i+'_'+jugador).innerHTML = "-";
				document.getElementById('gir'+i+'_'+jugador).value = 0;
			}
		}
		document.getElementById('girs_1_9_'+jugador).style.visibility = 'hidden';
		document.getElementById('girs_10_18_'+jugador).style.visibility = 'hidden';
	} else {
		par = document.getElementById('par'+forat).innerHTML;
		cops = document.getElementById('golpe'+forat+'_'+jugador).value;
		putts = document.getElementById('putt'+forat+'_'+jugador).value;
		//alert(par);
		
		if( (!isNaN(par)) && (cops != "") && (putts != "") ) {
			if( (cops - putts) > 0 ){
				if( cops - putts <= par - 2) {
					document.getElementById('green'+forat+'_'+jugador).innerHTML = '<img src="img/tick.png" alt="'+gir_si+'" title="'+gir_si+'" height="14" />';
					document.getElementById('gir'+forat+'_'+jugador).value = '1';
				} else {
					document.getElementById('green'+forat+'_'+jugador).innerHTML = '<img src="img/untick.png" alt="'+gir_no+'" title="'+gir_no+'" height="14" />';
					document.getElementById('gir'+forat+'_'+jugador).value = '0';
				}
			}else{
				document.getElementById('green'+forat+'_'+jugador).innerHTML = "-";
				document.getElementById('gir'+forat+'_'+jugador).value = '0';
				alert(error_putt);
				document.getElementById('putt'+forat+'_'+jugador).value = "";
			}
		} else {
			document.getElementById('green'+forat+'_'+jugador).innerHTML = "-";
			document.getElementById('gir'+forat+'_'+jugador).value = '0';
		}
		
 	}
}

// funcio que posa la primera lletra de cada paraula en majuscules
function changeCase(frmObj) {
	var index;
	var tmpStr;
	var tmpChar;
	var preString;
	var postString;
	var strlen;
	tmpStr = frmObj.value.toLowerCase();
	strLen = tmpStr.length;
	if (strLen > 0)  {
		for (index = 0; index < strLen; index++)  {
			if (index == 0)  {
				tmpChar = tmpStr.substring(0,1).toUpperCase();
				postString = tmpStr.substring(1,strLen);
				tmpStr = tmpChar + postString;
			}
			else {
				tmpChar = tmpStr.substring(index, index+1);
				if ( (tmpChar == " " || tmpChar == "-") && index < (strLen-1))  {
					tmpChar = tmpStr.substring(index+1, index+2).toUpperCase();
					preString = tmpStr.substring(0, index+1);
					postString = tmpStr.substring(index+2,strLen);
					tmpStr = preString + tmpChar + postString;
				}
			}
		}
	}
	frmObj.value = tmpStr;
}

/* COMPARATIVA TORNEOS */

// crida de l'autosuggest de participants
function get_participants(num_jugador,taula,valor,longitut){
	if(valor.length >= 1){
		var id_torneig = document.getElementById('hidden_torneig').value;
		var crida="ajax-autosuggest.php?target="+taula+"&t="+id_torneig+"&num_jugador="+num_jugador+"&str="+valor+"&length="+longitut;
		//alert(crida);
		cridaAJAX_cerca(crida);
	}else{
		document.getElementById(taula).innerHTML='';
	}
}

// callback de la taula generada amb els participants
function set_participant(id_jugador,num_jugador,str)
{
	var id_torneig = document.getElementById('hidden_torneig').value;
	var modalitat = document.getElementById('hidden_modalitat').value;
	document.getElementById('jugador_'+num_jugador).value=str;
	document.getElementById('autosuggest_'+num_jugador).innerHTML='';
	
	var crida="ajax-carrega-puntuacio-torneig.php?target=tr_jugador_"+num_jugador+"&t="+id_torneig+"&num_jugador="+num_jugador+"&j="+id_jugador+"&mod="+modalitat;
	cridaAJAX_cerca(crida);
}

// funcio per afegir una fila a la comparativa de jugadors d'un torneig
function afegir_participant(){
	var proper_id = parseInt(document.getElementById('next_player').value);
	var new_row = document.createElement('div');
	new_row.setAttribute('id','tr_jugador_'+proper_id);
	new_row.className = 'cmp_fila';
	document.getElementById('taula_comparativa').appendChild(new_row);
	
	var crida="ajax-add-player.php?target=tr_jugador_"+proper_id+"&n="+proper_id;
	cridaAJAX_cerca(crida);
	
	document.getElementById('next_player').value = proper_id+1;
}

function show_top5(){
	document.getElementById('capa_top5').style.display = 'block';	
	document.getElementById('capa_boton_ver_top5').style.display = 'none';
	document.getElementById('capa_boton_ocultar_top5').style.display = 'block';
}
function hide_top5(){
	document.getElementById('capa_top5').style.display = 'none';	
	document.getElementById('capa_boton_ocultar_top5').style.display = 'none';	
	document.getElementById('capa_boton_ver_top5').style.display = 'block';	
}

// funcio de comprovacio del formulari d'edicio de dades dels participants d'un torneig
function comprova_participants(){
	
	var num_players = document.getElementById('num_players').value;
	var i = 1;
	var tot_ok = true;
	
	for(i=1;i<=num_players;i++){
		if(document.getElementById('email_'+i)){
			if(document.getElementById('email_'+i).value.length > 0){
				if(!comprovaEmail(document.getElementById('email_'+i).value)){
					tot_ok = false;
					document.getElementById('email_'+i).style.backgroundColor = "#ff9191";
				}else if(document.getElementById('email_'+i).style.backgroundColor != ""){
					document.getElementById('email_'+i).style.backgroundColor = "";
				}
			}else if(document.getElementById('email_'+i).style.backgroundColor != ""){
				document.getElementById('email_'+i).style.backgroundColor = "";
			}
		}
	}
	
	if(tot_ok){
		document.form_participants.submit();
	}else{
		alert('Algun e-mail no es válido');	
	}
}

function todosmasculino()
{	
	num_players = document.getElementById("num_players").value;
	for(i=1; i<=num_players; i++)
	{			
		document.getElementById('radio'+i).checked = "checked";			
	}
}

//funcio que actualitza els horaris d'inscripcio segons el dia de torneig escollit
function actualitza_horaris(id_torneig,dia){
	var crida="ajax-combo-horaris.php?target=div_combo_horaris&t="+id_torneig+"&dia="+dia;
	cridaAJAX_cerca(crida);
}

//funcio que actualitza els horaris d'inscripcio segons el dia de torneig escollit per a tornejos amb SORTIDA SHOTGUN
function actualitza_horaris_shotgun(id_torneig,dia){
	var crida="ajax-combo-horaris-shotgun.php?target=div_combo_horaris&t="+id_torneig+"&dia="+dia;
	cridaAJAX_cerca(crida);
}

//funcio de validació del formulari d'inscripcio a un torneig
function valida_inscripcion(){
	
	//comprovem dia i hora
	if(document.getElementById("dia").value.length > 10 && document.getElementById("hora") && document.getElementById("hora").value != ""){
		//comprovem les dades del primer jugador
		if(document.getElementById("llicencia_1").value.length>0 && document.getElementById("nomcomplet_1").value.length>0 && document.getElementById("handicap_1").value.length>0 /*&& document.getElementById("email_1").value.length>0 && document.getElementById("telefon_1").value.length>0*/){
			//validació sexe
			if(!document.getElementById("sexe_f_1").checked && !document.getElementById("sexe_m_1").checked){
				alert(alert_sexe+" (*)");
				return (false);
			}else{
				//validació data naixement
				//if(document.getElementById("dia_1").value==0 || document.getElementById("mes_1").value==0 || document.getElementById("any_1").value==0){
				//	alert(alert_naixement+" (*)");
				//	return (false);
				//}else{
					
					if(document.getElementById("llicencia_1").value.length<10){
						alert(alert_licencia);
						return (false);
					}
					
					if(document.getElementById('email_1').value.length > 0 && !comprovaEmail(document.getElementById('email_1').value)){
						alert(email_invalido);
						return (false);
					}else{
						//validació del handicap
						document.getElementById("handicap_1").value = document.getElementById("handicap_1").value.replace(",", ".");
						if(isNaN(document.getElementById("handicap_1").value)){
							alert(alert_handicap);
							return(false);
						}else{
							var handicap = Number(document.getElementById("handicap_1").value);
							document.getElementById("handicap_1").value=handicap.toFixed(1);
							if(handicap>99 || handicap<-10){
								alert(handicap_incorrecto);
								return (false);
							}else{
								
								//comprovem les dades de la resta de jugadors (si n'hi ha)
								var array_llicencies = new Array();
								array_llicencies[1] = document.getElementById('llicencia_1').value;
								var array_mails = new Array();
								array_mails[1] = document.getElementById('email_1').value;
								
								max_jugadors = document.getElementById('persones_per_grup').value;
								for(j=2;j<=max_jugadors;j++){
									if(document.getElementById('llicencia_'+j)){
										if(document.getElementById("llicencia_"+j).value.length>0 && document.getElementById("nomcomplet_"+j).value.length>0 && document.getElementById("handicap_"+j).value.length>0){
											if(!document.getElementById("sexe_f_"+j).checked && !document.getElementById("sexe_m_"+j).checked){
												alert(alert_sexe_2);
												return (false);
											}else{
												//if(document.getElementById("dia_"+j).value==0 || document.getElementById("mes_"+j).value==0 || document.getElementById("any_"+j).value==0){
												//	alert(alert_naixement_2);
												//	return (false);
												//}else{
													if(document.getElementById('llicencia_'+j).value.length<10){
														alert(alert_licencias);
														return (false);
													}
													document.getElementById('handicap_'+j).value = document.getElementById('handicap_'+j).value.replace(",", ".");
													if(isNaN(document.getElementById('handicap_'+j).value)){
														alert(alert_handicaps);
														return(false);
													}
													if(document.getElementById('email_'+j).value.length > 0){
														if(!comprovaEmail(document.getElementById('email_'+j).value)){
															alert(alert_emails);
															return (false);
														}else{
															array_mails[j] = document.getElementById('email_'+j).value;
														}
													}
													array_llicencies[j] = document.getElementById('llicencia_'+j).value;
												//}
											}
										}else{
											alert(alert_camps_obligatoris_2);
											return (false);
										}
									}
								}
								
								// comprovem que no hi hagi llicencies repetides
								for(j=1;j<=max_jugadors;j++){
									for(k=1;k<=max_jugadors;k++){
										if(j != k){
											if(array_llicencies[j] && array_llicencies[j] == array_llicencies[k]){
												alert(alert_licencias_repetidas);
												return (false);
											}
										}
									}
								}
								
								// comprovem que no hi hagi mails repetits
								for(j=1;j<=max_jugadors;j++){
									for(k=1;k<=max_jugadors;k++){
										if(j != k){
											if(array_mails[j] && array_mails[j] == array_mails[k]){
												alert(alert_emails_repetidas);
												return (false);
											}
										}
									}
								}
								
								// pregunta de confirmació d'enviament
								if(confirm(pregunta_guardar_inscripcio)){
									// si arribem fins aquí, està tot bé, enviem el formulari
									document.getElementById('aux_return').value = document.getElementById('returnpath').value;
									document.form_inscripcions.submit();
									//alert('Enviem');
								}
							}
						}
					}
				//}
			}
			
		}else{
			alert(alert_camps_obligatoris+" (*)");
			return (false);
		}
		
	}else{
		alert(alert_dia_no_disponible);
		return (false);
	}
	
}

//comprova si cal mostrar el select de dies o el de voltes
function toggle_dies_voltes(valor){
	
	switch(valor){
		case '0': // 1 única volta
				document.getElementById('fila_voltes').style.display = 'none';
				document.getElementById('fila_dies').style.display = 'block';
		break;
		
		case '1': // multivolta
				document.getElementById('fila_voltes').style.display = 'block';
				document.getElementById('fila_dies').style.display = 'none';
		break;
		
		default:document.getElementById('fila_voltes').style.display = 'none';
				document.getElementById('fila_dies').style.display = 'block';
		break;
	}
}

//busqueda de datos segun el tee
function reload_tees(id_camp)
{
	var crida = "ajax-reload-tees.php?c="+id_camp+"&target=fila_tee";
	cridaAJAX_cerca(crida);
}

//cerca de modalitats segons el circuit
function reload_modalitats(id_circuit)
{
	var crida = "ajax-reload-modalitats.php?c="+id_circuit+"&target=fila_modalitat";
	cridaAJAX_cerca(crida);
}

//cerca de reglaments segons la modalitat
function reload_reglaments(id_modalitat)
{
	var crida = "ajax-reload-reglaments.php?mod="+id_modalitat+"&target=fila_reglament";
	cridaAJAX_cerca(crida);
}

//cerca de penalitzacions segons la modalitat
function reload_penalitzacions(id_modalitat)
{
	var crida = "ajax-reload-penalitzacions.php?mod="+id_modalitat+"&target=id_penalitzacio";
	cridaAJAX_cerca(crida);
}

//comprova si cal mostrar/amagar l'input de numero de millors targetes a computar segons el reglament seleccionat
function toggle_num_targetes(id_reglament,descripcio_reglament){
	// actualitzem la descripcio del reglament
	if(descripcio_reglament != null && descripcio_reglament != undefined)
		document.getElementById('desc_reg').innerHTML = descripcio_reglament;
	
	switch(id_reglament){
		case '1': // Participació única
				document.getElementById('fila_num_targetes').style.display = 'none';
				document.getElementById('num_millors_targetes').value = '0';
		break;
		
		case '2': // Participació múltiple
				document.getElementById('fila_num_targetes').style.display = 'block';
				document.getElementById('num_millors_targetes').value = '';
		break;
		
		default:document.getElementById('fila_num_targetes').style.display = 'none';
				document.getElementById('num_millors_targetes').value = '0';
		break;
	}
}

//actualitza la descripcio del reglament sobre el handicap del jugador durant el circuit
function toggle_handicap(valor_hcp,descripcio_hcp){
	if(valor_hcp != null && descripcio_hcp != undefined)
		document.getElementById('desc_hcp').innerHTML = descripcio_hcp;
	
}

//funcio per cridar l'spider de noms segons llicencia, i despres pintar el form de dades dels participants d'un torneig
function dades_participants_torneig(id,tipus){
	if(id != null && tipus != null){
		FAjax_inscripcio('ajax-torneo-participantes.php','taula_participants','t='+id+'&tip='+tipus,'post');
	}
}

/*** ADMINISTRADOR DE CAMP ***/
function valida_form_oferta(){
	if( document.getElementById('data_inici').value.length > 0 && document.getElementById('titol_cat').value.length > 0 && document.getElementById('titol_cast').value.length > 0 && document.getElementById('desc_cat').value.length > 0 && document.getElementById('desc_cast').value.length > 0){
		document.getElementById('desc_cat').value = ReplaceEnters(document.getElementById('desc_cat').value, true);
		document.getElementById('desc_cast').value = ReplaceEnters(document.getElementById('desc_cast').value, true);
		document.form_oferta.submit();
	}else{
		alert(alert_camps_obligatoris);
	}
}

function eliminar_oferta(id_oferta){
	if(confirm(confirma_elimnar_oferta)){
		document.location.href = "bd-eliminar-oferta.php?o="+id_oferta;
	}
}

// recarrega les ofertes segons el camp escollit (administradors de camps generics)
function administra_camp(id_camp){
	document.location.href = 'home-campos.php?c='+id_camp;	
}

// GESTOR INSCRIPCIONS
function carga_inscripcion(id_inscripcio){
	if(id_inscripcio!=null){
		FAjax_inscripcio('ajax-carrega-inscripcio.php','insc_'+id_inscripcio,'i='+id_inscripcio,'post');
	}
}
function borra_inscripcion(id_inscripcio){
	if(id_inscripcio!=null){
		document.getElementById('insc_'+id_inscripcio).style.backgroundColor = '#FF9191';
		var confirmacio = confirm(avis_esborrar_inscripcio);
		if(confirmacio){
			FAjax_inscripcio('ajax-esborra-inscripcio.php','insc_'+id_inscripcio,'i='+id_inscripcio,'post');
		}else{
			document.getElementById('insc_'+id_inscripcio).style.backgroundColor = '';
		}
	}
}

// validacio dels canvis a una inscripcio des del gestor d'inscripcions
function guarda_inscripcion(id_inscripcio){
	// aqui va tota la comprovacio
    var condicio=true;
    var text_alerta='';
	var dia = document.getElementById('dia_'+id_inscripcio).value;
	var hora = document.getElementById('hora_'+id_inscripcio).value;
	var llicencia = document.getElementById('llicencia_'+id_inscripcio).value;
	var nom = document.getElementById('nom_'+id_inscripcio).value;
	var email = document.getElementById('email_'+id_inscripcio).value;
	var telefon = document.getElementById('telf_'+id_inscripcio).value;
	var handicap = document.getElementById('hcp_'+id_inscripcio).value.replace(",", ".");
	var sexe = document.getElementById('sexe_'+id_inscripcio).value;
	var senior = 0;
	if(document.getElementById('senior_'+id_inscripcio).checked == true) senior = 1;
	var extras = document.getElementById('extras_'+id_inscripcio).value;
	var pagat = 0;
	if(document.getElementById('pagat_'+id_inscripcio).checked == true) pagat = 1;
    if(nom!='' && llicencia!='' && handicap!='' && hora!=''){
        hora_pattern = /^([0-1][0-9]|[2][0-3]):([0-5][0-9])$/;
        if( !hora_pattern.test(hora)){
            text_alerta += alert_hora+'\n';
            condicio = false;
        }
        if(llicencia.length<10){
            text_alerta += alert_licencia+'\n';
            condicio = false;
        }
		if(email.length>0 && !comprovaEmail(email)){
			text_alerta += email_invalido+'\n';
            condicio = false;
		}
        if(isNaN(handicap)){
            text_alerta += alert_handicap+'\n';
            condicio = false;
        }else{
            if(handicap>99 || handicap<-10){
				text_alerta += handicap_incorrecto+'\n';
				condicio = false;
			}
        }
    }else{
        text_alerta += alert_camps_obligatoris;
        condicio = false;
    }
    if(text_alerta!=''){
        alert(text_alerta);
    }
    
    if(condicio){
        FAjax_inscripcio('ajax-update-inscripcio.php','insc_'+id_inscripcio,'i='+id_inscripcio+'&dia='+dia+'&hora='+hora+'&llicencia='+llicencia+'&nom='+nom+'&email='+email+'&telefon='+telefon+'&handicap='+handicap+'&sexe='+sexe+'&senior='+senior+'&extras='+extras+'&pagat='+pagat,'post');
    }
}

// ********************* ALERTAS ************************ //

function request_alertas_camps(str) {
   //Don't forget to modify the path according to your theme
   myAjax.open("POST", "ajax_alertas_camps.php");
   myAjax.onreadystatechange = result;
   myAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
   myAjax.send("search="+str);
}

function selecciona_camp(id,logo,nom)
{
	amaga_tagupdate();
	if( (id != '') && (id != undefined) && (id != null)){
	   $('#afegir_camp').unbind('click');
       $('#afegir_camp').bind('click', function(){
	       afegeix_camp(id,logo,nom);
	   });  
    }
}

function afegeix_camp(id,logo,nom){
    if($('#campos_sigo div[id="'+id+'"]').html()){
    }else{
        $.ajax({
    		type: "POST",
            //dataType: 'json',
    		url: "ajax_alertas.php",
    		data: "id_jugador="+id_jugador+"&id_aux="+id+"&op=afegeix_camp" ,
    		beforeSend: function(){
    		      //$('#ajax_registre').css('display','block');
    		},
    		success: function(response){
                //$('#ajax_registre').css('display','none');
                if(id_jugador!='ko'){
                    $('#campos_sigo').append('<div id="'+id+'" class="fila"><a href=""><span class="foto"><img alt="logo" src="img/campos_s/'+logo+'"></span><span class="enlace"><span class="left">'+nom+'</span></span></a><div onclick="javascript:eliminar_camp('+id+')" class="x_eliminar">X</div></div>');
                }
            }
    	 });
    }
}

function eliminar_camp(id){
    $.ajax({
		type: "POST",
        //dataType: 'json',
		url: "ajax_alertas.php",
		data: "id_jugador="+id_jugador+"&id_aux="+id+"&op=elimina_camp" ,
		beforeSend: function(){
		      //$('#ajax_registre').css('display','block');
		},
		success: function(response){
            //$('#ajax_registre').css('display','none');
            if(id_jugador!='ko'){
                $('#campos_sigo div[id="'+id+'"]').remove();
            }
        }
	 });
}

function afegeix_circuit(){
    value = $('#select_circuito option:selected').val();
    text = $("#select_circuito option:selected").text();
    
    if($('#circuitos_sigo div[id="'+value+'"]').html() || value==-1 ){
    }else{
        $.ajax({
    		type: "POST",
            //dataType: 'json',
    		url: "ajax_alertas.php",
    		data: "id_jugador="+id_jugador+"&id_aux="+value+"&op=afegeix_circuit" ,
    		beforeSend: function(){
    		      //$('#ajax_registre').css('display','block');
    		},
    		success: function(response){
                //$('#ajax_registre').css('display','none');
                if(id_jugador!='ko'){
                    $('#circuitos_sigo').append('<div id="'+value+'" class="fila"><a href=""><span class="enlace"><span class="left">'+text+'</span></span></a><div onclick="javascript:eliminar_circuito('+value+')" class="x_eliminar">X</div></div>');
                }
            }
    	 });
    } 
}

function eliminar_circuito(id){
    $.ajax({
		type: "POST",
        //dataType: 'json',
		url: "ajax_alertas.php",
		data: "id_jugador="+id_jugador+"&id_aux="+id+"&op=elimina_circuit" ,
		beforeSend: function(){
		      //$('#ajax_registre').css('display','block');
		},
		success: function(response){
            //$('#ajax_registre').css('display','none');
            if(id_jugador!='ko'){
                $('#circuitos_sigo div[id="'+id+'"]').remove();
            }
        }
	 });
}

function actualitza_comunitat(id){   
    //if checked
    if($('#check_'+id).attr('checked')){
        $.ajax({
    		type: "POST",
            //dataType: 'json',
    		url: "ajax_alertas.php",
    		data: "id_jugador="+id_jugador+"&id_aux="+id+"&op=afegeix_comunitat" ,
    		beforeSend: function(){
    		      //$('#ajax_registre').css('display','block');
    		},
    		success: function(response){
                //$('#ajax_registre').css('display','none');
                if(id_jugador!='ko'){
                    
                }
            }
    	 });
    //if no checked    
    }else{
        $.ajax({
    		type: "POST",
            //dataType: 'json',
    		url: "ajax_alertas.php",
    		data: "id_jugador="+id_jugador+"&id_aux="+id+"&op=elimina_comunitat" ,
    		beforeSend: function(){
    		      //$('#ajax_registre').css('display','block');
    		},
    		success: function(response){
                //$('#ajax_registre').css('display','none');
                if(id_jugador!='ko'){

                }
            }
    	 });
    } 
}

function rebre_info(){
    if($('#rebre_info').attr('checked')){
        $('input').attr('disabled', true);
        $('#select_circuito').attr('disabled', 'disabled');
        $('#rebre_info').removeAttr('disabled');
    }else{
        $('input').removeAttr('disabled');
        $('#select_circuito').removeAttr('disabled');
    }
}

function edita_dades_ofertas(id_com,num_ofertes_destacades){
	FAjax_altres('ajax_ofertes_destacades.php','ajax_ofertas','&id_comunitat='+id_com+'&num_ofertes='+num_ofertes_destacades,'post'); 
}

// funcio per mostrar/amagar un div
function div_toggle(id_input){
	if(document.getElementById(id_input).checked){
		document.getElementById('div_'+id_input).style.display = 'block';
	}else{
		document.getElementById('div_'+id_input).style.display = 'none';
	}
}

var flag_primer=0;

//Per carregar el ranking de cadetes en el ranking de circuits
function cargaCadetes(e){
    if(flag_primer==0){
        $('#taula_amagada').html($('#taula_ranking_circuit').html());
        flag_primer++;
    }
    
    var engloba_pestanyes = $(e).parent().parent();
    $('.activa',$(engloba_pestanyes)).removeClass('activa').addClass('inactiva');
    $(e).parent().removeClass('inactiva').addClass('activa');
    
    $('#taula_ranking_circuit tr').each(function(){
         if($('.es_categoria',$(this)).attr('rel')!='C'){
            $('.es_categoria',$(this)).parent().css('display','none');
         }
    });
    var primer=1;
    var pos=1;
    var total=0;
    $('#taula_ranking_circuit tr').each(function(){
         if($('.es_categoria',$(this)).attr('rel')=='C'){
            //Li fico la primera posicio
            if(primer==1){ 
                $('.es_pos',$(this)).html(pos);
                total = $('.es_total',$(this)).attr('rel');
                primer=0;
            }else{
                //Si esta empatat amb l'anterior no printo pos
                if(total==$('.es_total',$(this)).attr('rel')){
                    $('.es_pos',$(this)).html(' ');
                }else{
                    $('.es_pos',$(this)).html(pos);
                }
            }
            total = $('.es_total',$(this)).attr('rel');
            pos++;
         }
    });
}

function cargaGeneral(e){
    var engloba_pestanyes = $(e).parent().parent();
    $('.activa',$(engloba_pestanyes)).removeClass('activa').addClass('inactiva');
    $(e).parent().removeClass('inactiva').addClass('activa');
    $('#taula_ranking_circuit').html($('#taula_amagada').html());
}

