/* Funcions JavaScript  */

function wordCount(texte) {
  // Función que nos va a contar el número de palabras del area de texto de un formulario

  // Obtenemos el texto del area.
  textoArea = texte.value;

  // Eliminamos los caracteres en blanco del inicio y del final.
  // Como no tenemos funciones del tipo trim, rtrim y ltrim usamos
  // expresiones regulares
  // El ^ indica principio de cadena
  inicioBlanco = /^ /
  // El $ indica final de cadena
  finBlanco = / $/
  // El global (g) es para obtener todas las posibles combinaciones
  variosBlancos = /[ ]+/g 

  textoArea = textoArea.replace(inicioBlanco,"");
  textoArea = textoArea.replace(finBlanco,"");
  textoArea = textoArea.replace(variosBlancos," ");

  // Creamos un array con las diferentes palabras. Teniendo en 
  // cuenta que la separación entre palabras es el espacio en blanco.
  textoAreaDividido = textoArea.split(" ");
  numeroPalabras = textoAreaDividido.length;
  
  return(numeroPalabras);
 }
 
 function recorta(str){
	return str.replace(/^(\s*)((\s*\S+)*)(\s*)$/,"$2");
}
 
 function obtenerValueRadioSeleccionado(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 textoVacio(texto){
	if ((texto == null) || (texto.length == 0))	return true;
	if (texto.search(/\S+/) != -1) return false;
	return true;
}

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 = /^[TXYZ]{1}/;
	var re2 = /^[T]{1}[A-Z0-9]{8}$/;
	var re3 = /X/;
	var re4 = /Y/;
	var re5 = /Z/;
	var strTmp = 'TRWAGMYFPDXBNJZSQVHLCKE';
	if(re.test(cf)){
		tmp = cf.replace(re3,'0');
		tmp = tmp.replace(re4,'1');
		tmp = tmp.replace(re5,'2');
		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 esMail(texto){
    var mailres = true;
    var cadena = "abcdefghijklmnñopqrstuvwxyzABCDEFGHIJKLMNÑOPQRSTUVWXYZ1234567890@._-";
    var arroba = texto.indexOf("@",0);
    if ((texto.lastIndexOf("@")) != arroba) arroba = -1;
    var punto = texto.lastIndexOf(".");
    for (var contador = 0 ; contador < texto.length ; contador++){
        if (cadena.indexOf(texto.substr(contador, 1),0) == -1){
            mailres = false;
            break;
     	}
    }
    if ((arroba > 1) && (arroba + 1 < punto) && (punto + 1 < (texto.length)) && (mailres == true) && (texto.indexOf("..",0) == -1))
    	mailres = true;
    else
    	mailres = false;

    return mailres;
}

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 = "";
		  },
		  onComplete: function(res) {
				$(id_div).innerHTML = res.responseText;
				setTimeout(function() {res.responseText.evalScripts()}, 1);
		}
	});	
}

 
