function cambiar(){
	$('capa_mitja').hide();
	$('capa_superior').hide();
}

function mostra_superior(width, height){
	/* el width i el height és l'amplada i l'altura del div on contindrà la informació */
	$('capa_mitja').show();	
	$('capa_superior').style.width = width;	
	$('capa_superior').style.height = height;
	$('capa_superior').style.marginLeft = (($('capa_superior').getWidth()*(-1))/2)+'px';
	$('capa_superior').style.marginTop = (($('capa_superior').getHeight()*(-1))/2)+'px';
	$('capa_superior').show();
	$('pagina').hide();
}

function descarrega_fitxer(id_fitxer, div_info){
	carregaURL('fitxers/descarrega_document_Ajax.php?id_fitxer='+id_fitxer, div_info);
}

function textoVacio(texto){
	if ((texto == null) || (texto.length == 0))	return true;
	if (texto.search(/\S+/) != -1) return false;
	return true;
}
function rangoAno(num){
	if(!esAno(num)) return false;
	if(num < 1980 || num > 2100){
		return false;
	}
	return true;
}
function esAno(num){
	var re = /^[0-9]{4}$/;
	if(re.test(num)){
		return true;
	}
	return false;
}

function _isInteger(val) {
	var digits="1234567890";
	for (var i=0; i < val.length; i++) {
		if (digits.indexOf(val.charAt(i))==-1) { return false; }
		}
	return true;
}
function _getInt(str,i,minlength,maxlength) {
	for (var x=maxlength; x>=minlength; x--) {
		var token=str.substring(i,i+x);
		if (token.length < minlength) { return null; }
		if (_isInteger(token)) { return token; }
		}
	return null;
}

function getDateFromFormat(val,format) {
	val=val+"";
	format=format+"";
	var i_val=0;
	var i_format=0;
	var c="";
	var token="";
	var token2="";
	var x,y;
	var now=new Date();
	var year=now.getYear();
	var month=now.getMonth()+1;
	var date=1;
	var hh=now.getHours();
	var mm=now.getMinutes();
	var ss=now.getSeconds();
	var ampm="";

	while (i_format < format.length) {
		// Get next token from format string
		c=format.charAt(i_format);
		token="";
		while ((format.charAt(i_format)==c) && (i_format < format.length)) {
			token += format.charAt(i_format++);
			}
		// Extract contents of value based on format token
		if (token=="yyyy" || token=="yy" || token=="y") {
			if (token=="yyyy") { x=4;y=4; }
			if (token=="yy")   { x=2;y=2; }
			if (token=="y")    { x=2;y=4; }
			year=_getInt(val,i_val,x,y);
			if (year==null) { return 0; }
			i_val += year.length;
			if (year.length==2) {
				if (year > 70) { year=1900+(year-0); }
				else { year=2000+(year-0); }
				}
			}
		else if (token=="MMM"||token=="NNN"){
			month=0;
			for (var i=0; i<MONTH_NAMES.length; i++) {
				var month_name=MONTH_NAMES[i];
				if (val.substring(i_val,i_val+month_name.length).toLowerCase()==month_name.toLowerCase()) {
					if (token=="MMM"||(token=="NNN"&&i>11)) {
						month=i+1;
						if (month>12) { month -= 12; }
						i_val += month_name.length;
						break;
						}
					}
				}
			if ((month < 1)||(month>12)){return 0;}
			}
		else if (token=="EE"||token=="E"){
			for (var i=0; i<DAY_NAMES.length; i++) {
				var day_name=DAY_NAMES[i];
				if (val.substring(i_val,i_val+day_name.length).toLowerCase()==day_name.toLowerCase()) {
					i_val += day_name.length;
					break;
					}
				}
			}
		else if (token=="MM"||token=="M") {
			month=_getInt(val,i_val,token.length,2);
			if(month==null||(month<1)||(month>12)){return 0;}
			i_val+=month.length;}
		else if (token=="dd"||token=="d") {
			date=_getInt(val,i_val,token.length,2);
			if(date==null||(date<1)||(date>31)){return 0;}
			i_val+=date.length;}
		else if (token=="hh"||token=="h") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<1)||(hh>12)){return 0;}
			i_val+=hh.length;}
		else if (token=="HH"||token=="H") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<0)||(hh>23)){return 0;}
			i_val+=hh.length;}
		else if (token=="KK"||token=="K") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<0)||(hh>11)){return 0;}
			i_val+=hh.length;}
		else if (token=="kk"||token=="k") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<1)||(hh>24)){return 0;}
			i_val+=hh.length;hh--;}
		else if (token=="mm"||token=="m") {
			mm=_getInt(val,i_val,token.length,2);
			if(mm==null||(mm<0)||(mm>59)){return 0;}
			i_val+=mm.length;}
		else if (token=="ss"||token=="s") {
			ss=_getInt(val,i_val,token.length,2);
			if(ss==null||(ss<0)||(ss>59)){return 0;}
			i_val+=ss.length;}
		else if (token=="a") {
			if (val.substring(i_val,i_val+2).toLowerCase()=="am") {ampm="AM";}
			else if (val.substring(i_val,i_val+2).toLowerCase()=="pm") {ampm="PM";}
			else {return 0;}
			i_val+=2;}
		else {
			if (val.substring(i_val,i_val+token.length)!=token) {return 0;}
			else {i_val+=token.length;}
			}
		}
	// If there are any trailing characters left in the value, it doesn't match
	if (i_val != val.length) { return 0; }
	// Is date valid for month?
	if (month==2) {
		// Check for leap year
		if ( ( (year%4==0)&&(year%100 != 0) ) || (year%400==0) ) { // leap year
			if (date > 29){ return 0; }
			}
		else { if (date > 28) { return 0; } }
		}
	if ((month==4)||(month==6)||(month==9)||(month==11)) {
		if (date > 30) { return 0; }
		}
	// Correct hours value
	if (hh<12 && ampm=="PM") { hh=hh-0+12; }
	else if (hh>11 && ampm=="AM") { hh-=12; }
	var newdate=new Date(year,month-1,date,hh,mm,ss);
	return newdate.getTime();
}


function isDate(val,format) {
	var date=getDateFromFormat(val,format);
	if (date==0) { return false; }
	return true;
}

function validarFecha(strFecha){
	if(isDate(strFecha,'dd-MM-yyyy')){ return true; }
	else{ return false; }

}

function validarFechaRelajada(strFecha){
	if(!isDate(strFecha,'dd-MM-yyyy')) {
		var arrFecha = strFecha.split("-");
		if(arrFecha.length != 3){ return false; }
		if(!esAno(arrFecha[2])){ return false; }
		if(!rangoAno(arrFecha[2])){ return false; }
		var re = /^((0[1-9])|(1([0-2])))$/;
		if(!re.test(arrFecha[1])){ return false; }
		if(arrFecha[0] != '00'){ return false; }
	}
	return true;
}

/*
	* Esta función clasifica y valida todos* los códigos fiscales que se usan en España.
	* Analiza una variable de 9 carácteres alfanuméricos y devuelve un valor numérico para cada tipo de código
	* analizado donde todos los valores positivos (mayores que cero) indican que el código fiscal es correcto.
	*
	* Los valores devueltos son:
	*
	* 	 1 = NIF válido
	* 	-1 = NIF no válido
	* 	 2 = CIF válido
	* 	-2 = CIF no válido
	* 	 3 = NIE válido
	* 	-3 = NIE no válido
	* 	 0 = código no válido
	*
	* La función cumple con todas las especificaciones de las leyes españolas:
	*
	* Decreto 2423/1975, de 25 de septiembre.
	* Real Decreto 338/1990, de 9 de marzo.
	* Real Decreto 1624/1992, de 29 de diciembre que modifica el 338/1990.
	* Real Decreto 155/1996, de 2 de febrero.
	* Orden de 3 de julio de 1998, por la que se modifica el Anexo del Decreto 2423/1975.
	*
	* Que es, actualmente, todo lo aprobado respecto con los Códigos de Identificación Fiscal,
	* Número de Identificación Fiscal y Número de Identificación de Extranjeros.
	*
	* *Nota: dado que el algoritmo del dígito de control usado es secreto y jamás ha sido publicado
	* en fuentes oficiales del Estado se ha usado un algoritmo obtenido por ingeniería inversa que ha
	* logrado validar correctamente alrededor de un millón de CIFs, NIFs y NIEs en total.
	* Con lo que, presumiblemente, se puede asumir que concuerda con el algoritmo de validación secreto original.
	*/
function valida_nif_cif_nie(cf) {
	cf = cf.toUpperCase();
	var num = new Array(9);
	for (var i = 0; i < 9; i++){
		num[i] = cf.substr(i,1);
	}

	//si no tiene un formato valido devuelve error
	var re = /((^[A-Z]{1}[0-9]{7}[A-Z0-9]{1}$|^[T]{1}[A-Z0-9]{8}$)|^[0-9]{8}[A-Z]{1}$)/;
	if(!re.test(cf)) return 0;

	//comprobacion de NIFs estandar
	re = /(^[0-9]{8}[A-Z]{1}$)/;
	if(re.test(cf)){
		var pat = 'TRWAGMYFPDXBNJZSQVHLCKE';
		if(num[8] == pat.substr(cf.substr(0,8) % 23, 1)) return 1;
		else return -1;
	}

	//algoritmo para comprobacion de codigos tipo CIF
	var suma = parseInt(num[2]) + parseInt(num[4]) + parseInt(num[6]);
	var tmp;

	for (var i = 1; i < 8; i += 2){
		tmp = 2 * num[i];
		suma += parseInt(String(tmp).substr(0,1));
		if(parseInt(String(tmp).substr(1,1))){
			suma += parseInt(String(tmp).substr(1,1));
		}
	}
	var n = 10 - parseInt(String(suma).substr(String(suma).length - 1, 1))

	//comprobacion de NIFs especiales (se calculan como CIFs)
	re = /^[KLM]{1}/;
	if(re.test(cf)){
		if(num[8] == String.fromCharCode(parseInt(64 + n))) return 1;
		else return -1;
	}

	//comprobacion de CIFs
	re = /^[ABCDEFGHNPQS]{1}/;
	if(re.test(cf)){
		if(num[8] == String.fromCharCode(parseInt(64 + n)) || num[8] == String(n).substr(String(n).length -1, 1) ) return 2;
		else return -2;
	}

	//comprobacion de NIEs
	re = /^[TX]{1}/;
	var re2 = /^[T]{1}[A-Z0-9]{8}$/;
	var re3 = /X/;
	var strTmp = 'TRWAGMYFPDXBNJZSQVHLCKE';
	if(re.test(cf)){
		tmp = cf.replace(re3,'0');
		tmp = tmp.substr(0,8)%23;
		tmp = strTmp.substr(tmp,1);
		if(num[8] == tmp || re2.test(cf) ) return 3;
		else return -3;
	}

	//si todavia no se ha verificado devuelve error
	return 0;
}

function esEnteroPositivo(str){
	var re = /^([0-9]+)$/;
	if(re.test(str)) return true;
	return false;
}

function recorta(str){
	return str.replace(/^(\s*)((\s*\S+)*)(\s*)$/,"$2");
}

function isEmailAddress(valor)
{
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(valor)){
		return (true)
	} else {
		return (false);
	}
}
function valor_radio(elementoRadio){
	var valor = false;
	if (elementoRadio.length==undefined){			
		//nomes i ha un sol element
		if (elementoRadio.checked){
			valor=elementoRadio.value;
		}
	}
	else {
		for (var i=0;i<elementoRadio.length;i++){
	       if (elementoRadio[i].checked){
				valor=elementoRadio[i].value;
				break;
			}
	    }
	}
	return valor;
}

function carregaURL(url,id_div){ // Funció Ajax per tractar dades
	new Ajax.Request(url, {
		  method: 'post',
		  asynchronous: true,
		  parameters:{},
		  onCreate: function(){
				$(id_div).innerHTML = "<center><img src='../img/loading.gif' /></center>";
		  },
		  onComplete: function(res) {
				$(id_div).innerHTML = res.responseText;
				setTimeout(function() {res.responseText.evalScripts()}, 1);
		}
	});
}

function carregaFormURL(url,id_div,f){ 
	var id_form = f.id;
	var params = Form.serialize($(id_form));	
	new Ajax.Request(url, {
		  method: 'post',
		  parameters: params,
		  asynchronous: true,
		  onCreate: function(){
				$(id_div).innerHTML = "<center><img src='../img/loading.gif' /></center>";
		  },
		  onComplete: function(res) {
				$(id_div).innerHTML = res.responseText;
				setTimeout(function() {res.responseText.evalScripts()}, 1);
		}
	});	

}


	
