/*******************/
/*  CROSS-BROWSER  */
/*******************/

function MM_findObj (n, d)	//v4.0
{
	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 && document.getElementById )
		x = document.getElementById(n);

	return x;
}



/**************/
/*  ROLLOVER  */
/**************/

/* 
	Usage:

	onLoad="MM_preloadImages('home_down.gif')"

	<a href="home.htm" onMouseOut="MM_swapImgRestore()" onMouseOver="MM_swapImage('homepage','','home_down.gif',0)">
		<img name="homepage" border="0" width="100" height="100" src="home_up.gif">
	</a>
*/

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_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_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];
		}
}



/************/
/*  ARRAYS  */
/************/

function AddData ( Tabla , Dato )
{
    Tabla[Tabla.length] = Dato
}

function RemoveData ( Tabla , index )
{
	for ( i = index ; i < Tabla.length ; i++ )
  {
		Tabla[i] = Tabla[i+1]
	}
	Tabla.length = Tabla.length - 1
}

function ChangeData ( Tabla , index , Dato )
{
	Tabla[index] = Dato
}



/*************************/
/*   VALIDACIÓN INPUTS   */
/*************************/
//Verifica k un campo tenga valor
function campoVacio( obj )
{
  if ( obj.value == "" )
    return 1
  else
    return 0
}

//limite máximo de caracteres para un objeto
function textLimit ( field , maxlen )
{
  if ( field.value.length > maxlen )
    field.value = field.value.substring( 0 , maxlen )
}



/*************/
/*  LISTBOX  */
/*************/
function CreateListBox ( Name, ListaLabel, ListaVal, Preselect, OnChg , filas, selmultiple , estilo)
{    
    Fil = ""
    if ( filas > 0 ) Fil = "SIZE=" + filas
    Mul = ""
    if ( selmultiple > 0 ) Mul = " MULTIPLE"
    document.write('<SELECT NAME=' + Name + ' VALUE="" '+ Fil + ' ONCHANGE="' + OnChg + '(this)"' + Mul + ' style="' + estilo + '">')
    if ( ListaLabel != 0 ) {
        for ( i = 0 ; i < ListaVal.length ; i++ ) {
            Sel = ""
            if ( ListaVal[i] == Preselect ) Sel = " SELECTED"
            document.write('<OPTION value="' + ListaVal[i] + '"' + Sel + '>' + ListaLabel[i] + '</OPTION>')
        }
    }
    document.write('</SELECT>')
}

function AddNewOption ( listbox_destino , texto , valor , defaultSel , sel )
{
	//antes se comprueba la existencia
	var isNew = true
	if ( listbox_destino.length > 0 )
	{
		for ( i=0 ; i < listbox_destino.length ; i++ )
		{
			if ( listbox_destino.options[i].value == valor )
			{
				isNew = false
				break
			}
		}
	}

	if ( isNew )	//no existe, entonces se añade
	{
		newoption = new Option( texto , valor , defaultSel , sel )  //new Option([text[, value[, defaultSelected[, selected]]]]) 
		listbox_destino.options[listbox_destino.length] = newoption
	}
	else	//ya existe, entonces se selecciona
	{
		listbox_destino.options[i].selected = true
	}
}

function DeleteOption ( obj_listbox )
{
	// Se construye un array con los valores de las opciones seleccionadas
	seleccionados = new Array()
	for ( i=0 ; i < obj_listbox.length ; i++ )
	{
		if ( obj_listbox.options[i].selected )
			AddData( seleccionados , obj_listbox.options[i].value )
	}

	// Se anulan todas las opciones seleccionadas
	for ( i=0 ; i < obj_listbox.length ; i++ )
	{
		for ( x=0 ; x < seleccionados.length ; x++ )
		{
			if ( obj_listbox.options[i].value == seleccionados[x] )
				obj_listbox.options[i] = null
		}
	}
}

function QuitarSeleccion ( obj_listbox )
{
	for ( i=0 ; i < obj_listbox.length ; i++ )
	{
		obj_listbox.options[i].selected = false
	}
}




/*************************/
/*   VALIDACIÓN EMAILS   */
/*************************/
//comprobación de dirección de email bien construida
function emailCheck ( emailStr )
{
  /* Verificar si el email tiene el formato user@dominio. */
  var emailPat=/^(.+)@(.+)$/ 
  /* Verificar la existencia de caracteres. ( ) < > @ , ; : \ " . [ ] */
  var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]" 
  /* Verifica los caracteres que son válidos en una dirección de email */
  var validChars="\[^\\s" + specialChars + "\]" 
  var quotedUser="(\"[^\"]*\")" 
  /* Verifica si la dirección de email está representada con una dirección IP Válida */ 
  var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/

  /* Verificar caracteres inválidos */ 
  var atom=validChars + '+'
  var word="(" + atom + "|" + quotedUser + ")"
  var userPat=new RegExp("^" + word + "(\\." + word + ")*$") /* domain, as opposed to ipDomainPat, shown above. */
  var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")

  var matchArray=emailStr.match(emailPat)
  if (matchArray==null)
  	return false

  var user=matchArray[1]
  var domain=matchArray[2]

  // Si el user "user" es valido 
  if (user.match(userPat)==null)
  	return false

  /* Si la dirección IP es válida */
  var IPArray=domain.match(ipDomainPat)
  if (IPArray!=null)
  {
    for (var i=1;i<=4;i++)
    {
      if (IPArray[i]>255)
        return false
    }
    return true
  }
  
  var domainArray=domain.match(domainPat)
  if (domainArray==null)
    return false

  var atomPat=new RegExp(atom,"g")
  var domArr=domain.match(atomPat)
  var len=domArr.length
  if (domArr[domArr.length-1].length<2 || domArr[domArr.length-1].length>3)
  	return false

  if (len<2)
  	return false


  // La dirección de email ingresada es Válida
  return true;
}


/*************************/
/*   VALIDACIÓN NIF      */
/*************************/

function nifCheck(el_nif)
{
	return valida_nif_cif_nie(el_nif); //Nueva Funcion que valida el NIF CIF NIE
	//return  validarNifNieDni(el_nif);
}

function validarNifNieDni(el_nif)
{  
 var temp=el_nif.toUpperCase();
 temp = temp.replace(/[ -.]/gi,"");
 var cadenadni="TRWAGMYFPDXBNJZSQVHLCKET";
 var v1 = new Array(0,2,4,6,8,1,3,5,7,9);
 if ( temp.length > 8 )
 {
  // No es un CIF ni un NIE, es un DNI
  if (!/^[ABCDEFGHKLMNPQSX]/.test(temp))
  {
   //Tiene los 9 dígitos, comprobamos si la letra esta bien
   posicion = temp.substring(8,0) % 23; /*Resto de la division entre 23 es la posicion en la cadena*/
   letra = cadenadni.charAt(posicion);
   var letradni=temp.charAt(8);
   if (letra != letradni)
   {
    //La Letra del DNI no es correcta
    return false;
   }
   correcto = temp.substring(9,0);
   
  }
  else
  { 
   //Es un NIE o un CIF
   if (/^[X]/.test(temp))//Es un NIE
   { 
    var temp1=temp.substr(1,7);
    posicion = temp1 % 23; /*Resto de la division entre 23 es la posicion en la cadena*/
    letra = cadenadni.charAt(posicion);
    var letranie=temp.charAt(8);
    if (letra != letranie){
     //La letra del NIE no es correcta
     return false;   
    }
    correcto = temp.substring(9,0);
   }
   else //Es un CIF
   { 
    var cifcontrol = 0;
    for( i = 2; i <= 6; i += 2 )
    {
     cifcontrol = cifcontrol + v1[ parseInt(temp.substr(i-1,1)) ];
     cifcontrol = cifcontrol + parseInt(temp.substr(i,1));
    }
    cifcontrol = cifcontrol + v1[ parseInt(temp.substr(7,1)) ];
    cifcontrol = (10 - ( cifcontrol % 10));
    if (cifcontrol!=temp.substr(8,1))
    {
      //El dígito de control del CIF no es correcto
         return false;   
    }
    correcto = temp.substring(9,0);
   }
  }
  return correcto;
 }
 else
 {
  return false;
 }
}
function valida_nif_cif_nie(a) 
{
	var temp=a.toUpperCase();
	var DNI_NIE=a.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 false;
		}
 
		//comprobacion de NIFs estandar
		if (/^[0-9]{8}[A-Z]{1}$/.test(temp))
		{
			posicion = a.substring(8,0) % 23;
			letra = cadenadni.charAt(posicion);
			var letradni=temp.charAt(8);
			if (letra == letradni)
			{
			   	return DNI_NIE;
			}
			else
			{
				return false;
			}
		}
 
		//algoritmo para comprobacion de codigos tipo CIF
		suma = parseInt(a[2])+parseInt(a[4])+parseInt(a[6]);
		for (i = 1; i < 8; i += 2)
		{
			temp1 = 2 * parseInt(a[i]);
			temp1 += '';
			temp1 = temp1.substring(0,1);
			temp2 = 2 * parseInt(a[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 (a[8] == String.fromCharCode(64 + n))
			{
				return DNI_NIE;
			}
			else
			{
				return false;
			}
		}
 
		//comprobacion de CIFs
		if (/^[ABCDEFGHJNPQRSUVW]{1}/.test(temp))
		{
			temp = n + '';
			if (a[8] == String.fromCharCode(64 + n) || a[8] == parseInt(temp.substring(temp.length-1, temp.length)))
			{
				return DNI_NIE;
			}
			else
			{
				return false;
			}
		}
 
		//comprobacion de NIEs
		//T
		if (/^[T]{1}/.test(temp))
		{
			if (a[8] == /^[T]{1}[A-Z0-9]{8}$/.test(temp))
			{
				return DNI_NIE;
			}
			else
			{
				return false;
			}
		}
 
		//XYZ
		if (/^[XYZ]{1}/.test(temp))
		{
			pos = str_replace(['X', 'Y', 'Z'], ['0','1','2'], temp).substring(0, 8) % 23;
			if (a[8] == cadenadni.substring(pos, pos + 1))
			{
				return DNI_NIE;
			}
			else
			{
				return false;
			}
		}
	}
 
	return false;
}
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];
}



/*************************/
/*   VALIDACIÓN FECHAS   */
/*************************/
function EsBisiesto(anio)
{
  if ( (anio % 100 != 0) && ((anio % 4 == 0) || (anio % 400 == 0)) )
    return true
  else
    return false
}

function esFechaValida( f , format )
{
  //Devuelve:
  //  0   fecha no introducida
  //  -1  formato no válido
  //  -2  fecha errónea
  //  1   FECHA OK

  if ( f == undefined || f.value == "" )
    return 0
  
  fecha = f.value.replace(/-/g,"/")
  formato = format.replace(/-/g,"/")

  if ( !/^\d{2}\/\d{2}\/\d{4}$/.test(fecha) )
    return -1

  if ( formato == "dd/mm/aaaa" )
  {
    var dia  =  parseInt( fecha.substring(0,2) , 10 )
    var mes  =  parseInt( fecha.substring(3,5) , 10 )
    var anio =  parseInt( fecha.substring(6) , 10 )
  }
  else if ( formato == "mm/dd/yyyy" )
  {
    var mes  =  parseInt( fecha.substring(0,2) , 10 )
    var dia  =  parseInt( fecha.substring(3,5) , 10 )
    var anio =  parseInt( fecha.substring(6) , 10 )
  }

  switch(mes)
  {
    case 1: //Enero, Marzo, Mayo, Julio, Agosto, Octubre, Diciembre
    case 3:
    case 5:
    case 7:
    case 8:
    case 10:
    case 12:
      numDias = 31
      break;
    
    case 4: //Abril, Junio, Septiembre, Noviembre 
    case 6:
    case 9:
    case 11:
      numDias = 30
      break;
    
    case 2: //Febrero
      if ( EsBisiesto(anio) )
        numDias = 29
      else
        numDias = 28
      break;
    default:
      return -2
  }

  if ( dia>numDias || dia==0 )
    return -2

  return 1
}

function YDDiff(years,days)
{
  this.years = years;
  this.days = days;
}

YDDiff.prototype.toString = function() { return this.years + "y" + this.days +"d"; };

function diffYearAndDate(d1,d2)
{
  // ensure d1 <= d2
  if (d1 > d2) { return diffYearAndDate(d2,d1); }

  // find n whole years later than d1 in d2's year.
  var dt = new Date(d1);
  dt.setFullYear(d2.getFullYear());
  // n whole years later > d2
  var overflow = (dt > d2);
  // max whole years later than d1 less than d2
  dt = new Date(d1);
  dt.setFullYear(d2.getFullYear() - overflow);
  // whole years from d1 to dt
  var years = dt.getFullYear() - d1.getFullYear();
  // days from dt to d2, less than whole year from dt
  var days = Math.round((d2 - dt)/864e5);

  return new YDDiff(years,days);
}

function TiempoTranscurrido( fecha_desde , fecha_hasta , bDias /*Devuelve los dias de diferencia*/ )
{  
  var obj_diff = diffYearAndDate( fecha_desde , fecha_hasta )
  
  if ( bDias )
    return obj_diff.days
  else
    return obj_diff.years  
}



/*************************/
/*  VALIDACIÓN NUMEROS   */
/*************************/
function esEntero ( numero )
{
  regexp = /^[0-9]+$/
  return ( regexp.test(numero) )
}

function esReal ( numero )
{
	regexp = /^[0-9]*[\.][0-9]*$/
	return ( regexp.test(numero) )
}

function esNumero ( valor )
{
  if ( esEntero(valor) )
    return 1
  else if ( esReal(valor) )
    return 2
  else
    return 0
}




/*************/
/*   CAPAS   */
/*************/
function MostrarOcultarCapa( capa )
{
  if ( document.getElementById(capa) )
  {
    if  ( document.getElementById(capa).style.display == "none" )
      document.getElementById(capa).style.display = ""
    else
      document.getElementById(capa).style.display = "none"
  }
}




/**********/
/*  AJAX  */
/**********/

function GetXmlHttpObject()
{
  var xmlHttp = null

  try
  {
    xmlHttp = new XMLHttpRequest()  // Firefox, Opera 8.0+, Safari
  }
  catch (e)
  {
    // Internet Explorer
    try
    {
      xmlHttp = new ActiveXObject("Msxml2.XMLHTTP")
    }
    catch (e)
    {
      xmlHttp = new ActiveXObject("Microsoft.XMLHTTP")
    }
  }

  return xmlHttp
}


function CargarPagina ( pagina_requerida , id_contenedor )
{
  if (pagina_requerida.readyState == 4 && (pagina_requerida.status == 200 || window.location.href.indexOf ("http") == - 1))
  {
    txt = unescape(pagina_requerida.responseText)
    txt2 = txt.replace(/\+/gi," ")
    try
    {
      if ( document.getElementById(id_contenedor).tagName == "INPUT" )
        document.getElementById(id_contenedor).value = txt2
      else
        document.getElementById(id_contenedor).innerHTML = txt2
    }
    catch (e)
    {
      // IE fails unless we wrap the string in another element
      var wrappingDiv = document.createElement('div')
      wrappingDiv.innerHTML = txt2
      document.getElementById(id_contenedor).appendChild(wrappingDiv)
    }
  }
}

function Llamada_GET( url , id_contenedor )
{
  //Agregamos el timestamp a la url para k el servidor no cachee
  var sep = "&" ;
  if ( url.substr(url.length-4) == ".php" )
    sep = "?"

  var date = new Date()
  var url_send = url + sep + "tmst=" + date.valueOf()


  var pagina = GetXmlHttpObject()

  pagina.onreadystatechange = function ()
  {
    CargarPagina ( pagina , id_contenedor )
  }
  pagina.open ( 'GET' , url_send , true )
  pagina.send ( null )
}

function Llamada_POST( url , parametros , id_contenedor )
{
  var pagina = GetXmlHttpObject()

  pagina.onreadystatechange = function ()
  {
    CargarPagina ( pagina , id_contenedor )
  }
  pagina.open( 'POST' , url , true )
  pagina.setRequestHeader( "Content-type" , "application/x-www-form-urlencoded" )
  //pagina.setRequestHeader( "Content-type" , "text/html; charset=ISO-8859-1" )
  //pagina.setRequestHeader( "Charset" , "ISO-8859-1" )
  pagina.setRequestHeader( "Content-length" , parametros.length )
  pagina.setRequestHeader( "Connection" , "close" )
  pagina.send( parametros )
}

/**********/
/*  MISC  */
/**********/
function sleep(milliseconds)
{
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++)
  {
    if ((new Date().getTime() - start) > milliseconds)
      break;
  }
}

