
// Funcion que se encarga de la redireccion
function redirector (url, origen, nuevaVentana, widthVentana, heightVentana) {

	// Parseo url
	while (url.indexOf('?') >= 0) {
		url = url.replace("?","%3F");
	}
	while (url.indexOf('&') >= 0) {
		url = url.replace("&","%26");
	}
    
	// Construyo destino
	var destino = "/jsp/r.jsp?origen="+origen+"&url="+url;

	// Variables ventana
	if (typeof(nuevaVentana) == "undefined") {
		nuevaVentana = false;
	}
	if (typeof(widthVentana) == "undefined") {
		widthVentana = 0;
	}
	if (typeof(heightVentana) == "undefined") {
		heightVentana = 0;
	}

	// Realizo redireccion	
	if (nuevaVentana) {
		if (widthVentana == 0 || heightVentana == 0) {
			abrirVentana(destino, '', (screen.width - 60), (screen.height - 270));
		} else {
			abrirPopup(destino, '', widthVentana, heightVentana);
		}
	} else {
		document.location = destino;
	}
}

function calcularPosicion(x, y) {
	if (x == y) {
		return 0;
	} else {
		return Math.round((x/2)-(y/2));
	}
}

// Abre una ventana
function abrirVentana(url,name,w,h) {
	var posx2 = calcularPosicion(screen.width, w);
	var posy2 = calcularPosicion(screen.height, h);
	if (posy2 > 160) {
		posy2 -= 160;
	}

	var newWindow = window.open(url,name,'resizable=1,scrollbars=1,status=1,location=1,toolbar=1,menubar=1,width='+w+',height='+h+',screenX='+posx2+',screenY='+posy2+',left='+posx2+',top='+posy2+'');
	if (typeof(newWindow) != "undefined") {
		newWindow.focus();
	}
}

// Abre un popup
function abrirPopup(url,name,w,h) {
	var posx2 = calcularPosicion(screen.width, w);
	var posy2 = calcularPosicion(screen.height, h);
	if (posy2 > 30) {
		posy2 -= 30;
	}

	var newWindow = window.open(url,name,'resizable=0,scrollbars=0,status=0,location=0,toolbar=0,menubar=0,width='+w+',height='+h+',screenX='+posx2+',screenY='+posy2+',left='+posx2+',top='+posy2+'');
	if (typeof(newWindow) != "undefined") {
		newWindow.focus();
	}
}

// Obtiene un elemento de la pagina a partir de su identificador (id)
function el(id) {
  if (document.getElementById) {
    return document.getElementById(id);
  } else if (window[id]) {
    return window[id];
  }
  return null;
}
//Recupera un form a partir de su nombre (name) o el primer formulario si se llama sin parametros.
function form(nombre) {
	if (nombre==null || typeof(nombre)=="undefined")
		return document.forms[0];
	else return document.forms[nombre];
}
//Devuelve un campo de un formulario a partir de nombre formulario (o objeto form) y nombre campo o solo de nombre campo (primer formulario).
function campo(nombreForm,nombreCampo)
{
	var formulario;
	if (nombreCampo==null || typeof(nombreCampo)=="undefined"){
		//Se ha llamado s?lo con nombre de campo
		formulario=form();
		nombreCampo=nombreForm;
	}else if (typeof(nombreForm)!="string"){
		//Se asume que pasan el objeto form.
		formulario=nombreForm;
	}else{
		formulario=form(nombreForm);
	}
	return formulario.elements[nombreCampo];
}

function changeIdioma(idioma, pais) {
	saveCookie("cookieidioma", idioma, true);	
	saveCookie("cookiepais", pais, true);	
	document.location.reload();
}

//rellena con caracteres a la izquierda la cadena hasta tener las posiciones deseadas.
function lpad(cadena,caracter,posiciones)
{
	for(;posiciones>cadena.length;)
		cadena = caracter + cadena;
	return cadena.substring(cadena.length-posiciones);
}
//rellena con caracteres a la derecha la cadena hasta tener las posiciones deseadas.
function rpad(cadena,caracter,posiciones)
{
	for(;posiciones>cadena.length;)
		cadena = cadena + caracter;
	return cadena.substring(0,posiciones);
}
function trim(cadena) {
	for(i=0; i<cadena.length; )	{
		if (cadena.charAt(i)==" ")
			cadena = cadena.substring(i+1, cadena.length);
		else
			break;
	}

	for(i=cadena.length-1; i>=0; i=cadena.length-1)	{
		if (cadena.charAt(i)==" ")
			cadena=cadena.substring(0,i);
		else
			break;
	}
	return cadena;
}
//Establece el testo de un tag span (si es null o undefined, pone "").
//(verifica compatibilidad con IE o Mozilla).
function setTexto(span,valor)
{
	//Valor vacio.
	if (typeof(valor)=="undefined" || valor==null) valor="";

	//Compatibilidad navegador.
	if(innerTextSupported==null)
		innerTextSupported = typeof(span.innerText)!="undefined";

	//Escribir el texto
	if (innerTextSupported) span.innerText=valor;
	else span.textContent=valor;
}
var innerTextSupported=null;


function validarCIF(nif_cif) {
   // if ((comprobarCif(nif_cif) && (validarCif(nif_cif))) || (esNif(nif_cif)))
   if (esNif(nif_cif))
   	return true;
   else if (comprobarCif(nif_cif) && (validarCif(nif_cif)))
//   if ((comprobarCif(nif_cif) && (validarCif(nif_cif))) && (!esNif(nif_cif)))
		return true;
	else
		alert("El CIF/NIF introducido no es correcto");
		return false;
}

function esNif(valor) {
	if(valor.length == 9) {
		valor = valor.toUpperCase();
		var posibles = new Array("T","R","W","A","G","M","Y","F","P","D","X","B","N","J","Z","S","Q","V","H","L","C","K","E");
		if(isNumeric(valor.substring(0,8))) {
			var aux = parseFloat (valor.substring(0,8));
			aux = aux % 23;
			return valor.charAt(8) == posibles[aux];
		}else{
			if(valor.substring(0,1) == 'X'){
				var aux = parseFloat (valor.substring(1,8));
				aux = aux % 23;
				return valor.charAt(8) == posibles[aux];
			}else{
				return false;
			}
		}
	}else{
		
		return false;
	}
}

// Funcion que comprueba la entrada de datos 
function comprobarCif(cif)  
{ 
  var resul = false; 
  var temp = cif.toUpperCase(); // pasar a may?sculas 
  if (!/^[A-Za-z0-9]{9}$/.test(temp))
  {  // Son 9 d?gitos?  
	alert("El CIF debe constar de 9 digitos");
	 cif.focus();
	 resul = false;

  }else if (!/^[ABCDEFGHJKLMNPQRSUVW]/.test(temp)) {// Es una letra de las admitidas ? 

	resul = false;

 } else if (!isNumeric(temp.substr(1,7))){
	
	resul = false;

 } else  {

     resul = true; 
}
  return resul; 
} 


function validarCif(cif)  
{ 
  
  var v1 = new Array(0,2,4,6,8,1,3,5,7,9);  
  var temp = 0;  
  var temp1; 

   
  for( i = 2; i <= 6; i += 2 )  
    { 
      temp = temp + v1[ parseInt(cif.substr(i-1,1)) ]; 
      temp = temp + parseInt(cif.substr(i,1)); 
    }; 

  temp = temp + v1[ parseInt(cif.substr(7,1)) ]; 

  temp = (10 - ( temp % 10)); 

  if( temp == 10 ) 
	return (cif.substr(8,1).toUpperCase() == 'J' || cif.substr(8,1) == 0);
    //alert( "El d?gito de control es: J ? 0" ); 
  else 
	return (cif.substr(8,1) == temp);
    //alert( "El d?gito de control es: "+temp );  
    return true;
}

function isNumeric(value) {
	var val = new Number(value);
	if (isNaN(val)) {
		return false;
	}else{
		return true;
	}
}


function validarCif(texto)
{

var pares = 0;
var impares = 0;
var suma;
var ultima;
var unumero;
var uletra = new Array("J", "A", "B", "C", "D", "E", "F", "G", "H", "I");
var xxx;

texto = texto.toUpperCase();

var regular = new RegExp(/^[ABCDEFGHJKLMNPQRSUVW]\d\d\d\d\d\d\d[0-9,A-J]$/g);
if (!regular.exec(texto)) return false;

ultima = texto.substr(8,1);

for (var cont = 1 ; cont < 7 ; cont ++){
	xxx = (2 * parseInt(texto.substr(cont++,1))).toString() + "0";
	impares += parseInt(xxx.substr(0,1)) + parseInt(xxx.substr(1,1));
	pares += parseInt(texto.substr(cont,1));
}
xxx = (2 * parseInt(texto.substr(cont,1))).toString() + "0";
impares += parseInt(xxx.substr(0,1)) + parseInt(xxx.substr(1,1));

suma = (pares + impares).toString();
unumero = parseInt(suma.substr(suma.length - 1, 1));
unumero = (10 - unumero).toString();
if(unumero == 10) unumero = 0;

if ((ultima == unumero) || (ultima == uletra[unumero]))
	return true;
else
	return false;
}


function isNumeric(value) {
	var val = new Number(value);
	if (isNaN(val)) {
		return false;
	}else{
		return true;
	}
}



// Funcion que valida el formato de un email
function validaFormatoEmail1(email) {

	var posArroba = email.indexOf("@");
	var posUltimoPunto = email.lastIndexOf(".");

	if(posArroba < 1 || posArroba == (email.length - 1))
		return false;

	if(posUltimoPunto < posArroba || posUltimoPunto == (email.length - 1)) 
		return false;

	if(posUltimoPunto + 1 == posArroba) 
		return false;

	return true;
}

// Funci?n que valida el formato de un email
function validaFormatoEmail2 (email) {

	var checkTLD=1;
	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum|cat)$/;
	var emailPat=/^(.+)@(.+)$/;
	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
	var validChars="\[^\\s" + specialChars + "\]";
	var quotedUser="(\"[^\"]*\")";
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
	var atom=validChars + '+';
	var word="(" + atom + "|" + quotedUser + ")";
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
	var matchArray=email.match(emailPat);
	var user=matchArray[1];
	var domain=matchArray[2];
	var IPArray=domain.match(ipDomainPat);
	var atomPat=new RegExp("^" + atom + "$");
	var domArr=domain.split(".");
	var len=domArr.length;

	if (matchArray==null)
		return false; 

	for (i=0; i<user.length; i++) {
		if (user.charCodeAt(i)>127) 
			return false;
	}

	for (i=0; i<domain.length; i++) {
		if (domain.charCodeAt(i)>127)
			return false;
	}

	if (user.match(userPat)==null)
		return false;

	if (IPArray!=null) {
		for (var i=1;i<=4;i++) {
			if (IPArray[i]>255)
				return false;
		}
		return true;
	}

	for (i=0;i<len;i++) {
		if (domArr[i].search(atomPat)==-1)
			return false;
	}

	if (checkTLD && domArr[domArr.length-1].length!=2 && domArr[domArr.length-1].search(knownDomsPat)==-1)
		return false;

	if (len<2)
		return false;
 

	return true;
}

function cerrarVentana()
{
	window.close();
}
function abrirRegistroLoginCS()
{
	window.opener.location='/PGC/registro.gas';
	window.close();
}
//Deshabilita todos los enlaces y formularios.
function disableForms() {
	if (document.all || document.getElementById) {
		var anchorsArray = document.anchors;
		//alert('Hay ' + anchorsArray.length + ' anchors.');
		for (i = 0; i < anchorsArray.length; i++) {
			var tempAnchor = anchorsArray[i];
			//alert(tempAnchor);
			tempAnchor.onClick = 'return false;';
			tempAnchor.href = '#';
		}

		var linksArray = document.links;
		//alert('Hay ' + linksArray.length + ' links.');
		for (i = 0; i < linksArray.length; i++) {
			var tempLink = linksArray[i];
			//alert(tempLink);
			tempLink.onClick = 'return false;';
			tempLink.href = '#';
		}

		var formsArray = document.forms;
		//alert('Hay ' + formsArray.length + ' forms.');
		for (i = 0; i < formsArray.length; i++) {
			var theform = formsArray[i];
			for (j = 0; j < theform.elements.length; j++) {
				var tempobj = theform.elements[j];
				//alert(tempobj.type);
				if (tempobj.type.toLowerCase() == "submit" || tempobj.type.toLowerCase() == "reset") {
					tempobj.disabled = true;
				}
			}
    	}
    	
    return true;

	} else {
		//alert("The form has been submitted.  But, since you're not using IE 4+ or NS 6, the submit button was not disabled on form submission.");
		return false;
	}
}

function abrirPopup_seguridad() {
	var opciones="toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,width=800,height=625,top=85,left=140";
	var w = window.open(tratarLink(MSG['RecomendacionesSeguridad.url']),"seguridad",opciones);
	if (typeof(w) != "undefined") {
		w.focus();
	}
}

function abrirPopup_legal() {
	var opciones="toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,width=800,height=625,top=85,left=140";
	var w = window.open(tratarLink(MSG['NotaLegal.url']),"legal",opciones);
	if (typeof(w) != "undefined") {
		w.focus();
	}
}

// Las variables hostSecure y host se definen en la cabecera de CS
function tratarLink(link) {
	if (link.indexOf("/PGC/") == 0) {
		if (typeof(hostSecure) == "undefined") hostSecure = "";
		link = hostSecure + link;
	} else if (link.indexOf("/servlet/") == 0) {
		if (typeof(host) == "undefined") host = "";
		link = host + link;
	}
	return link;
}

