
/************/
/*  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 FECHAS   */
/*************************/
function EsBisiesto(anio)
{
  if ( (anio % 100 != 0) && ((anio % 4 == 0) || (anio % 400 == 0)) )
    return true
  else
    return false
}

function esFechaValida( fecha , formato )
{
  //Devuelve:
  //  0   fecha no introducida
  //  -1  formato no válido
  //  -2  fecha errónea
  //  1   FECHA OK

  if ( fecha == undefined || fecha.value == "" )
    return 0
  
  if ( !/^\d{2}\/\d{2}\/\d{4}$/.test(fecha.value) )
    return -1

  if ( formato == "dd/mm/aaaa" )
  {
    var dia  =  parseInt( fecha.value.substring(0,2) , 10 )
    var mes  =  parseInt( fecha.value.substring(3,5) , 10 )
    var anio =  parseInt( fecha.value.substring(6) , 10 )
  }
  else if ( formato == "mm/dd/yyyy" )
  {
    var mes  =  parseInt( fecha.value.substring(0,2) , 10 )
    var dia  =  parseInt( fecha.value.substring(3,5) , 10 )
    var anio =  parseInt( fecha.value.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
}



/*****************/
/*  FORMULARIOS  */
/*****************/

function campoObligatorio( obj , lbl_campo )
{
  if ( obj.tagName == "SELECT" )
  {
    if ( obj.value == 0 )
    {
      alert( 'Debe especificar el campo ' + '"' + lbl_campo + '"' )
      obj.focus()
      return 0
    }
  }
  else
  {
    if ( campoVacio(obj) )
    {
      alert( '"' + lbl_campo + '" no puede estar vacío' )
      obj.focus()
      return 0
    }
  }

  return 1
}

function fechaValida ( obj )
{
  var formato = "dd/mm/aaaa"
  var ret = esFechaValida ( obj , formato )
  
  if ( ret == -1 )
  {
    alert( 'Formato de fecha erróneo (' + formato + ')' )
    obj.value = ""
    obj.focus()
    return false
  }
  else if ( ret == -2 )
  {
    alert('Fecha incorrecta')
    obj.value = ""
    obj.focus()
    return false
  }
  
  return true
}


function numeroValido ( obj )
{
  if ( obj.value == "" )
    return
  
  ret = esNumero( obj.value )
  //alert(ret)
  if ( !ret )
  {
    alert( 'Número no válido' )
    obj.value = ""
    obj.focus()
  }  
}

function enteroValido ( obj )
{
  if ( obj.value == "" )
    return
  
  ret = esEntero( obj.value )
  if ( !ret )
  {
    alert( 'Entero no válido' )
    obj.value = ""
    obj.focus()
  }  
}


function campoEmail( obj )
{
  if ( obj.value != "" )
  {
    if ( ! emailCheck(obj.value) )
    {
      alert( 'Email no válido' )
      obj.focus()
      return 0
    }
  }

  return 1
}




/*************/
/*   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 )
}