// JavaScript Document
function abre_fichero(file,titulo,ancho,alto)
{
 var danch = (screen.availWidth / 2)-(ancho/2); 
 var dalt = (screen.availHeight / 2)-(alto/2); 
 kk_file=window.open('', 'kk_file', 'width='+ ancho +', height='+ alto +', top='+ dalt +',left='+ danch +', toolbar=no, scrollbars=no, menubar=no, location=no, resizable=yes'); 
 kk_file.document.write('<html><head><title>'+ titulo +'</title></head><body marginheight=0 marginwidth=0 topmargin=0 leftmargin=0><iframe width=100% height=100% frameborder=0 marginheight=0 marginwidth=0 hspace=0 vspace=0 src='+ file +'></iframe></body></html>');
}
function abre_pagina(pagina,ancho,alto)
{
 var danch = (screen.availWidth / 2)-(ancho/2); 
 var dalt = (screen.availHeight / 2)-(alto/2); 
 poput=window.open(pagina,'ventana','status=no,resizable=yes,scrollbars=yes,width='+ ancho +',height='+ alto +',top='+ dalt +',left='+ danch)
}

function reemplazarIntros(cual)
{
texto = cual.value
intro=new RegExp(String.fromCharCode(10),"g")
cual.value=texto.replace(intro,"<br>")
//alert (cual.value) //esto lo puedes sacar. Lo pongo para que veas al instante el resultado
}

function formatodecimal(cantidad, decimales) {
    decimales = (!decimales ? 2 : decimales); // 2 decimales por defecto.
	return Math.round(cantidad * Math.pow(10, decimales)) / Math.pow(10, decimales);  
} 

function difer_fecha(fecha_ini, fecha_fin)
{
 //alert(fecha_ini +" "+ fecha_fin);
 var ini_partes = fecha_ini.split("/");
 var ini_anyo = ini_partes[2];
 var ini_mes = ini_partes[1];
 var ini_dia = ini_partes[0];
 var ini = new Date(ini_anyo,ini_mes-1,ini_dia);		
 
 var fin_partes = fecha_fin.split("/");
 var fin_anyo = fin_partes[2];
 var fin_mes = fin_partes[1];
 var fin_dia = fin_partes[0];
 var fin = new Date(fin_anyo,fin_mes-1,fin_dia);	
 //alert(fin_anyo +" "+ fin_mes +" "+ fin_dia);
 //alert(fin);
 var dias = (fin.getTime() - ini.getTime()) / (1000*60*60*24);
 var dias = Math.floor(dias);
 //alert(dias);
 return dias;
}

function long_num (longitud,num) {
	// Fuerza la longitud de $num poniendo ceros a la izquierda
	var nuevo = String(num);
	if (String(num).length < longitud) {
		ceros = longitud - String(num).length;
		for(i = 0; i < ceros; i++) nuevo = '0'+ nuevo; 
	}
	return nuevo;	
} // Fin de long_num()

function suma_mes(fecha_ini, meses) {
	meses = parseInt(meses);
	var ini_partes = fecha_ini.split("/");
	var anyo = (ini_partes[2]*1);
	var mes = (ini_partes[1]*1) + meses;
	var dia = (ini_partes[0]*1);
	
	if (mes > 12) {
		mes = (mes%12);
		anyo = anyo + Math.floor(((ini_partes[1]*1) + meses) / 12);
		if (mes==0) { 
			mes = 12; 
			anyo = anyo-1; 
		}
	}
	m_days = Array (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
	if (anyo % 4 == 0 && (anyo % 100 > 0 || anyo % 400 == 0)) {
		m_days[1] = 29; // non leap-years can be: 1700, 1800, 1900, 2100, etc.
	}
	
	if (dia > m_days[mes-1]) dia = m_days[mes-1];
	salida = long_num(2,dia)+"/"+long_num(2,mes)+"/"+long_num(4,anyo);
	return salida;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function MM_goToURL() { //v3.0
  var i, args=MM_goToURL.arguments; document.MM_returnValue = false;
  for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
}

/*document.onkeydown = function(){
	if(window.event && window.event.keyCode == 116){ window.event.keyCode = 505; } 
    if(window.event && window.event.keyCode == 505){ return false; }  
}*/

// Función para la comprobación del email
function isEmailAddress(theElement){
	var s = theElement.value;
	var filter=/^[A-Za-z][A-Za-z0-9_.-]*@[A-Za-z0-9_-]+\.[A-Za-z0-9_.-]+[A-za-z]$/;
	if (s.length == 0 ) return true;
		if (filter.test(s))
			return true;
		theElement.focus();
	return false;
}

// Funciones para la conversión de un número de decimal a hexadecimal
function decConvertToBase(num, base)
{
	var newNum="";
	var result=num;
	var remainder=0;
	while (result>0)
	{
		result=Math.floor(num/base);
		remainder=num%base;
		num=result;
		
		if (remainder>=10)
		{
			if (remainder==10)
				remainder='A';
			if (remainder==11)
				remainder='B';
			if (remainder==12)
				remainder='C';
			if (remainder==13)
				remainder='D';
			if (remainder==14)
				remainder='E';
			if (remainder==15)
				remainder='F';
		}
		// just append the next remainder to the beginning of the string
		newNum=""+remainder+newNum;
	};
	return newNum;
}   

function decToHex(decNum)
{	
	var hexNum=decConvertToBase(decNum, 16);
	
	return hexNum;
}   
// Fin de funciones para la conversión de un número de decimal a hexadecimal

function valida_nif_cif_nie(doc) {
//devuelve: 1 = NIF ok, 2 = CIF ok, 3 = NIE ok, -1 = NIF bad, -2 = CIF bad, -3 = NIE bad, 0 = ??? bad
	doc=doc.toUpperCase();
	var filtro = /^[A-Z]{1}[0-9]{7}[A-Z0-9]{1}$|^[T]{1}[A-Z0-9]{8}$|^[0-9]{8}[A-Z]{1}$/;
	if(!filtro.test(doc)) 
		return 0;
	var num = new Array(9);
	for (i=0;i<9;i++)
	{
		num[i]=doc.substring(i,i+1);		
	}
	var suma = parseInt(num[2])+parseInt(num[4])+parseInt(num[6]);
	
	for(i=1;i<8;i+=2)
	{		
		var cad = (2*num[i]) + '';	
		var primero = parseInt(cad.substring(0,1));		
		var segundo = cad.substring(1,2);		
		if(segundo =="")
			segundo = 0;
		else
			segundo = parseInt(segundo);			
						
		suma+=primero+segundo;		
	}
	suma=suma+'';
	suma=suma.substring(suma.length-1,suma.length);
	var n=10-suma;		
	var num_ascii = decToHex(64 + n);			
	num_ascii = '%' + num_ascii;
	n = n + '';
	var letras='TRWAGMYFPDXBNJZSQVHLCKE';
	
	filtro = /^[ABCDEFGHNPQS]{1}/;		
	if(filtro.test(doc))
	{		
		if(num[8]==unescape(num_ascii) || num[8]==n.substring(n.length-1,n.length)) { return 2; } else { return -2; }		
	}
	filtro = /^[KLM]{1}/;
	if(filtro.test(doc))
	{
		if(num[8]==unescape(num_ascii)) { return 2; } else { return -2;}
	}
	filtro = /^[TX]{1}/;
	var filtro2 = /^[T]{1}[A-Z0-9]{8}$/;
	if(filtro.test(doc))
	{
		cad=doc.substring(0,8);		
		var pos=cad.replace('X','0')%23;		
		if(num[8]==letras.substring(pos,pos+1) || filtro2.test(doc)) { return 3; } else { return -3;}
	}
	filtro = /^[0-9]{8}[A-Z]{1}$/;
	if(filtro.test(doc))
	{
		cad=doc.substring(0,8);
		pos=cad%23;	
		if(num[8]==letras.substring(pos,pos+1)) { return 1; } else { return -1;}
	}	
	return 0;
}

function str_replace(search, replace, subject) {
    var f = search, r = replace, s = subject;
    var ra = r instanceof Array, sa = s instanceof Array, f = [].concat(f), r = [].concat(r), i = (s = [].concat(s)).length;
 
    while (j = 0, i--) {
        if (s[i]) {
            while (s[i] = s[i].split(f[j]).join(ra ? r[j] || "" : r[0]), ++j in f){};
        }
    };
 
    return sa ? s : s[0];
}

function NEW_valida_nif_cif_nie(doc) {
	var temp=doc.toUpperCase();
	var cadenadni="TRWAGMYFPDXBNJZSQVHLCKE";
 
	if (temp!==''){
		//si no tiene un formato valido devuelve error
		if ((!/^[A-Z]{1}[0-9]{7}[A-Z0-9]{1}$/.test(temp) && !/^[T]{1}[A-Z0-9]{8}$/.test(temp)) && !/^[0-9]{8}[A-Z]{1}$/.test(temp))
		{
			return 0;
		}
 
		//comprobacion de NIFs estandar
		if (/^[0-9]{8}[A-Z]{1}$/.test(temp))
		{
			posicion = doc.substring(8,0) % 23;
			letra = cadenadni.charAt(posicion);
			var letradni=temp.charAt(8);
			if (letra == letradni)
			{
				return 1;
			}
			else
			{
				return 0;
			}
		}
 
		//algoritmo para comprobacion de codigos tipo CIF
		suma = parseInt(doc.charAt(2))+parseInt(doc.charAt(4))+parseInt(doc.charAt(6));
		for (i = 1; i < 8; i += 2)
		{
			temp1 = 2 * parseInt(doc.charAt(i));
			temp1 += '';
			temp1 = temp1.substring(0,1);
			temp2 = 2 * parseInt(doc.charAt(i));
			temp2 += '';
			temp2 = temp2.substring(1,2);
			if (temp2 == '')
			{
				temp2 = '0';
			}
 
			suma += (parseInt(temp1) + parseInt(temp2));
		}
		suma += '';
		n = 10 - parseInt(suma.substring(suma.length-1, suma.length));
 
		//comprobacion de NIFs especiales (se calculan como CIFs)
		if (/^[KLM]{1}/.test(temp))
		{
			if (doc.charAt(8) == String.fromCharCode(64 + n))
			{
				return 1;
			}
			else
			{
				return 0;
			}
		}
 
		//comprobacion de CIFs
		if (/^[ABCDEFGHJNPQRSUVW]{1}/.test(temp))
		{
			temp = n + '';
			if (doc.charAt(8) == String.fromCharCode(64 + n) || doc.charAt(8) == parseInt(temp.substring(temp.length-1, temp.length)))
			{
				return 1;
			}
			else
			{
				return 0;
			}
		}
 
		//comprobacion de NIEs
		//T
		if (/^[T]{1}/.test(temp))
		{
			if (doc.charAt(8) == /^[T]{1}[A-Z0-9]{8}$/.test(temp))
			{
				return 1;
			}
			else
			{
				return 0;
			}
		}
 
		//XYZ
		if (/^[XYZ]{1}/.test(temp))
		{
			pos = str_replace(['X', 'Y', 'Z'], ['0','1','2'], temp).substring(0, 8) % 23;
			if (doc.charAt(8) == cadenadni.substring(pos, pos + 1))
			{
				return 1;
			}
			else
			{
				return 0;
			}
		}
	}		 
	return 0;	
}

function anyoBisiesto(anyo)
{
	/**
	* si el año introducido es de dos cifras lo pasamos al periodo de 1900. Ejemplo: 25 > 1925
	*/
	if (anyo < 100)
		var fin = anyo + 1900;
	else
		var fin = anyo ;
	
	/*
	* primera condicion: si el resto de dividir el año entre 4 no es cero > el año no es bisiesto
	* es decir, obtenemos año modulo 4, teniendo que cumplirse anyo mod(4)=0 para bisiesto
	*/
	if (fin % 4 != 0)
		return false;
	else
	{
		if (fin % 100 == 0)
		{
			/**
			* si el año es divisible por 4 y por 100 y divisible por 400 > es bisiesto
			*/
			if (fin % 400 == 0)
			{
				return true;
			}
			/**
			* si es divisible por 4 y por 100 pero no lo es por 400 > no es bisiesto
			*/
			else
			{
				return false;
			}
		}
		/**
		* si es divisible por 4 y no es divisible por 100 > el año es bisiesto
		*/
		else
		{
			return true;
		}
	}
}

function MuestraElem(idElem) {
	$("#"+idElem).show();
}
function OcultaElem(idElem) {
	$("#"+idElem).hide();
}

function addBookmark(title,url) {
	if (window.sidebar) { 
		window.sidebar.addPanel(title, url,""); 
	} else if( document.all ) {
		window.external.AddFavorite( url, title);
	} else if( window.opera && window.print ) {
		return true;
	}
}

function nuevoAjax()
{ 
	/* Crea el objeto AJAX. Esta funcion es generica para cualquier utilidad de este tipo, por
	lo que se puede copiar tal como esta aqui */
	var xmlhttp=false; 
	try 
	{ 
		// Creacion del objeto AJAX para navegadores no IE
		xmlhttp=new ActiveXObject("Msxml2.XMLHTTP"); 
	}
	catch(e)
	{ 
		try
		{ 
			// Creacion del objet AJAX para IE 
			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
		} 
		catch(E) { xmlhttp=false; }
	}
	if (!xmlhttp && typeof XMLHttpRequest!='undefined') { xmlhttp=new XMLHttpRequest(); } 

	return xmlhttp; 
}
