// 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;
	}
}
/*** 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)); }
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_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;
	var llicencia_golf = document.getElementById('llicencia_golf').value;
	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');
	
	// 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
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";
}

//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 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;
		}
	}
}

//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('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.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('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);
					}
				}
			}
		}
		
		
		// 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);
	}
	
	// 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(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(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' ) {
		form.action = "registro.php";
		form.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('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' ){
		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: . = 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;
	} 
	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 >= 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;
			
		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);
        }
    }

}

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 = 'editar_torneo.php?t='+id_torneo+'&e='+id_noticia;
		}
	}
}


// funcio de validacio del formulari de login dels organitzadors de tornejos
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 per validar el formulari d'editar torneig
function valida_torneo(){
	if(document.getElementById('tee').value != 0){
		document.form_torneo.submit();
	}else{
		alert(error_falta_tee);	
	}
}

// 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 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){
		FAjax_altres('ajax_torneo_ranking_detalles.php','taula_ranking','t='+id,'post');
	}
}

//funcio per actualitzar el ranking d'un torneig al mode detallat
function ranking_totales(id,categoria){
	if(id != null){
		FAjax_altres('ajax_torneo_ranking_totales.php','taula_ranking','t='+id+'&c='+categoria,'post');
	}
}

//funcio per actualitzar el ranking d'un torneig al mode classificacio SCRATCH
function ranking_scratch(id){
	if(id != null){
		FAjax_altres('ajax_torneo_ranking_scratch.php','taula_ranking','t='+id,'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 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 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;
			}
		}
		document.getElementById('girs_1_9').style.visibility = 'hidden';
		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 = "border: 1px solid red;";
				}
			}
		}
	}
	
	if(tot_ok){
		document.form_participants.submit();
	}else{
		alert('ko');	
	}
}

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