
/*************/
/*   FORMS   */
/*************/

function campoVacio( obj )
{
  if ( obj.value == "" )
    return 1
  else
    return 0
}

function textLimit ( field , maxlen )
{
  if ( field.value.length > maxlen )
    field.value = field.value.substring( 0 , maxlen )
}

//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;
}

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*/ )
{  
//  alert( fecha_desde.toString() )
//  alert( fecha_hasta.toString() )
  
  var obj_diff = diffYearAndDate( fecha_desde , fecha_hasta )
  
  if ( bDias )
    return obj_diff.days
  else
    return obj_diff.years  
}

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
}


function SetCheckValue ( form_name , obj , input_hidden , multiple )
{
  var f = document.forms[form_name]

  obj_input = eval( form_name + '.' + input_hidden )
  valor_actual = obj_input.value

  if ( multiple )
  {
    if ( obj.checked )
      obj_input.value = Number(valor_actual) + Number(obj.value)
    else
      obj_input.value = Number(valor_actual) - Number(obj.value)
  }
  else
  {
    if ( obj.checked )
      obj_input.value = 1
    else
      obj_input.value = 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"
  }
}



/*************/
/*  WINDOWS  */
/*************/

function NuevaVentana ( url , target , width , height , top , left , location , toolbar , scrollbar , resizable , directories , menubar , status )
{
	if ( width == null )
    width = screen.width

	if ( height == null )
    height = screen.height - 100

  if ( top == null )
		top = (screen.height - height - 100) / 2

	if ( left == null )
		left = (screen.width - width) / 2

	if ( location == null )
		location = 'no'

	if ( toolbar == null )
		toolbar = 'no'

	if ( scrollbar == null )
		scrollbar = 'yes'

	if ( resizable == null )
			resizable = 'no'

	if ( directories == null )
		directories = 'no'

	if ( menubar == null )
		menubar = 'no'

	if ( status == null )
		status = 'no'


	params = "width=" + width + ",height=" + height + ",top=" + top + ",left=" + left + ",toolbar=" + toolbar + ",scrollbars=" + scrollbar + ",resizable=" + resizable + ",menubar=" + menubar + ",status=" + status ;

	var v = window.open( url , target , params ) ;

	v.focus()
}


// Moves the box object to be directly beneath an object.
function move_box(an, box)
{
    var cleft = 0;
    var ctop = 0;
    var obj = an;

    while (obj.offsetParent)
    {
        cleft += obj.offsetLeft;
        ctop += obj.offsetTop;
        obj = obj.offsetParent;
    }

    box.style.left = cleft + 'px';

    ctop += an.offsetHeight + 8;

    // Handle Internet Explorer body margins,
    // which affect normal document, but not
    // absolute-positioned stuff.
    if (document.body.currentStyle &&
        document.body.currentStyle['marginTop'])
    {
        ctop += parseInt(
            document.body.currentStyle['marginTop']);
    }

    box.style.top = ctop + 'px';
}

// Shows a box if it wasn't shown yet or is hidden
// or hides it if it is currently shown
function show_hide_box(an, width, height, borderStyle)
{
    var href = an.href;
    var boxdiv = document.getElementById(href);

    if (boxdiv != null)
    {
        if (boxdiv.style.display=='none')
        {
            // Show existing box, move it
            // if document changed layout
            move_box(an, boxdiv);
            boxdiv.style.display='block';

            bringToFront(boxdiv);

            // Workaround for Konqueror/Safari
            if (!boxdiv.contents.contentWindow)
                boxdiv.contents.src = href;
        }
        else
            // Hide currently shown box.
            boxdiv.style.display='none';
        return false;
    }

    // Create box object through DOM
    boxdiv = document.createElement('div');

    // Assign id equalling to the document it will show
    boxdiv.setAttribute('id', href);

    boxdiv.style.display = 'block';
    boxdiv.style.position = 'absolute';
    boxdiv.style.zIndex = 10;
    boxdiv.style.width = width + 'px';
    boxdiv.style.height = height + 'px';
    boxdiv.style.border = borderStyle;
    boxdiv.style.textAlign = 'right';
    boxdiv.style.padding = '4px';
    boxdiv.style.background = '#f0f0f0';
    document.body.appendChild(boxdiv);

    var offset = 0;

    // Remove the following code if 'Close' hyperlink
    // is not needed.
    var close_href = document.createElement('a');
    close_href.href = 'javascript:void(0);';
    close_href.className = 'x_close';
    /*close_href.style.color = 'red';
    close_href.style.font = 'bold 16px Courier';
    //close_href.style.text-decoration = 'none';*/
    close_href.onclick = function()
        { show_hide_box(an, width, height, borderStyle); }
    close_href.appendChild(document.createTextNode('X'));
    boxdiv.appendChild(close_href);
    offset = close_href.offsetHeight;
    // End of 'Close' hyperlink code.

    var contents = document.createElement('iframe');
    //contents.scrolling = 'no';
    contents.overflowX = 'hidden';
    contents.overflowY = 'scroll';
    contents.frameBorder = '0';
    contents.style.width = width + 'px';
    contents.style.margin = '5px 0px 0px 0px';
    contents.style.height = (height - offset - 10) + 'px';

    boxdiv.contents = contents;
    boxdiv.appendChild(contents);

    move_box(an, boxdiv);

    if (contents.contentWindow)
        contents.contentWindow.document.location.replace(
            href);
    else
        contents.src = href;

    // The script has successfully shown the box,
    // prevent hyperlink navigation.
    return false;
}

function getAbsoluteDivs()
{
    var arr = new Array();
    var all_divs = document.body.getElementsByTagName("DIV");
    var j = 0;

    for (i = 0; i < all_divs.length; i++)
        if (all_divs.item(i).style.position=='absolute')
        {
            arr[j] = all_divs.item(i);
            j++;
        }

    return arr;
}

function bringToFront(obj)
{
    if (!document.getElementsByTagName)
        return;

    var divs = getAbsoluteDivs();
    var max_index = 0;
    var cur_index;

    // Compute the maximal z-index of
    // other absolute-positioned divs
    for (i = 0; i < divs.length; i++)
    {
        var item = divs[i];
        if (item == obj ||
            item.style.zIndex == '')
            continue;

        cur_index = parseInt(item.style.zIndex);
        if (max_index < cur_index)
        {
            max_index = cur_index;
        }
    }

    obj.style.zIndex = max_index + 1;
}




/*******************/
/*  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 , Dato )
{
  var index = -1 //index of element to be removed in the array

	for ( i = 0 ; i < Tabla.length ; i++ )
  {
    if ( Tabla[i] == Dato )
    {
      index = i
      break;
    }
	}

  if ( index > -1 )
    Tabla.splice(index,1)
}

function ChangeData ( Tabla , index , Dato )
{
	Tabla[index] = Dato
}



/*************/
/*  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
	}
}



/**********/
/*  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))
  {
    try
    {
//if ( id_contenedor == 'stats_votes' )
//  alert(pagina_requerida.responseText)

      document.getElementById(id_contenedor).innerHTML = pagina_requerida.responseText
    }
    catch (e)
    {
      // IE fails unless we wrap the string in another element
      var wrappingDiv = document.createElement('div')
      wrappingDiv.innerHTML = pagina_requerida.responseText
      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-length" , parametros.length )
  pagina.setRequestHeader( "Connection" , "close" )
  pagina.send( parametros )
}
