/**********************************************
*trim
*
*	Trim
*
*
**********************************************/
function trim(a)
{
	var txt = a;
	while(txt.length > 0)
		if (txt.charAt(0) == ' ')
			txt = txt.substring(1, txt.length);
		else
			break;

	while(txt.length > 0)
		if (txt.charAt(txt.length-1) == ' ')
			txt = txt.substring(0, txt.length-1);
		else
			break;
	return txt;
}

/**********************************************
*addOptSelect
*
*	Agrega la opcion <txt> al select <sel>
*	Si se utiliza el parametro <val>, se toma
*	 como valor de la opcion.
*
**********************************************/
function addOptSelect(sel, txt, val)
{
	var cant = sel.length;
	var existe = false;
	for (var i=0; i<cant; i++){
		//if (sel.options[i].text == txt){
		if (sel.options[i].value == val){
			existe = true;
			return false;
		}
	}
	if (!existe){
		if (val + "" == "undefined")
			var newOp = new Option(txt, cant);
		else
			var newOp = new Option(txt, val);
		sel[cant] = newOp;
//	    alert(val);
//	    alert(sel[cant].value);
	}
	return true;
}

/**********************************************
*addOptSelectForce
*
*	Agrega la opcion <txt> al select <sel>
*	Si se utiliza el parametro <val>, se toma
*	 como valor de la opcion.
*
**********************************************/
function addOptSelectForce(sel, txt, val)
{
	var cant = sel.length;
	var existe = false;
	if (!existe){
		if (val + "" == "undefined")
			var newOp = new Option(txt, cant);
		else
			var newOp = new Option(txt, val);
		sel[cant] = newOp;
//	    alert(val);
//	    alert(sel[cant].value);
	}
	return true;
}

/**********************************************
*delOptSelect
*
*	Elimina la opcion numero <n> del select <sel>
**********************************************/
function delOptSelect(sel, n)
{
	var cant = sel.length;
	if (n < cant && n >= 0)
		sel.options[n] = null;
	else
		return false;
	cant = sel.length;
	if (cant > 0){
		if (n < cant)
			sel.options[n].selected = true;
		else
			sel.options[cant-1].selected = true;
	}
	return true;
}

/**********************************************
*selectOptionText
*
*	Selecciona la opcion con texto <txt> del select <sel>
**********************************************/
function selectOptionText(sel, txt)
{
	var cant = sel.length;
	for (var i=0; i<cant; i++){
		if (sel.options[i].text == txt){
			sel.options[i].selected = true;
			return true;
		}
	}
	return false;
}

/**********************************************
*selectOptionValue
*
*	Selecciona la opcion con valor <val> del select <sel>
**********************************************/
function selectOptionValue(sel, val)
{
	var cant = sel.length;
	for (var i=0; i<cant; i++){
		if (sel.options[i].value == val){
			sel.options[i].selected = true;
			return true;
		}
	}
	return false;
}

/**********************************************
*checkNumber
*
*	Verifica que los caracteres de <txt> sean numericos (positivos)
**********************************************/
function checkNumber(txt)
{
	var flag = true;

	for (var i=0; i<txt.length; i++)
		if (txt.charAt(i) < '0' || txt.charAt(i) > '9'){
			flag = false;
			break;
		}
	return flag;
}

/**********************************************
*checkNumberWithSignus
*
*	Verifica que los caracteres de <txt> sean numericos (positivos y negativos)
**********************************************/
function checkNumberWithSignus(txt)
{
	var flag = true;

	for (var i=0; i<txt.length; i++)
		if (txt.charAt(i) < '0' || txt.charAt(i) > '9'){
			if (i != 0 || txt.charAt(i) != '-') {
				flag = false;
				break;
			}
		}
	return flag;
}
/**********************************************
*checkInt
*
*	Verifica que <txt> sea entero
**********************************************/
function checkIntNotEmpty(txt)
{
  var flag = true;
  if (txt.length == 0){
    return false;
  }else{
    var i=0;
    if (txt.charAt(0) == '-'){
      if (txt.length > 1){
        i = 1;
      }else{
        return false;
      }
    }
    for (; i<txt.length; i++)
      if (txt.charAt(i) < '0' || txt.charAt(i) > '9'){
        flag = false;
        break;
      }
  }
  return flag;
}

/**********************************************
*convertNumber
*
*	recibe un n?mero decimal, cuyo separador
*   decimal sea puto o coma. Si es coma lo
*   reemplaza por punto.
**********************************************/
function convertNumber(txt) {
  var res = txt;
  for (i=txt.length; i>=0; i--) {
    if (txt.charAt(i) == ',') {
	  if (i > 0 && i< txt.length) {
	    res = txt.substring(0, i)+"."+txt.substring(i+1, txt.length);
	  }
      break;
    }
  }
  return res;
}

/**********************************************
*checkDecNotEmptyPrec2
*
*	Verifica que <txt> sea un entero o decimal con
* a lo sumo 2 lugares de precis??n decimales
**********************************************/

function checkDecNotEmptyPrec2(txt)
{
  return checkDecNotEmpty(txt,2);
}

/**********************************************
*checkDecNotEmpty
*
*  Verifica que <txt> sea un entero o decimal con
*  a lo sumo maxDecimals lugares de precis??n
*  decimales
**********************************************/

function checkDecNotEmpty(txt,maxDecimals)
{
  var flag = true;
  if (txt.length == 0){
    return false;
  }else{
    var i=0;
    if (txt.charAt(0) == '-'){
      if (txt.length > 1){
        i = 1;
      }else{
        return false;
      }
    }
//valido que
    if (txt.charAt(i) < '0' || txt.charAt(i) > '9') {
      return false;
    }else{
      i = i+1;
    }

    var flagHaySepDec=false;
    var cantPrec=0;
    for (; i<txt.length; i++){
      if (txt.charAt(i) < '0' || txt.charAt(i) > '9') {
//Si es el ?nico punto o coma y no es el caracter final
        if ((txt.charAt(i) == '.' || txt.charAt(i) == ',') && !flagHaySepDec && txt.length-1>i){
          flagHaySepDec=true;
        }else{
          flag = false;
          break;
        }
      }else{
        if (flagHaySepDec){
          cantPrec = cantPrec + 1;
        }
      }
      if (cantPrec>maxDecimals){
        flag = false;
        break;
      }
    }
  }
  return flag;
}

/**********************************************
*checkText
*
*	Verifica que <txt> no sea nulo
**********************************************/
function checkText(txt)
{
	if (txt.length == 0)
		return false;
	else
		return true;
}

/**********************************************
*checkSymbols
*
*	Verifica que <txt> no contenga simbolos
**********************************************/
function checkSymbolsAndSp(txt)
{
	for (var i=0; i<txt.length; i++){
		if (!((txt.charAt(i) >= 'A' && txt.charAt(i) <= 'Z')
			|| (txt.charAt(i) >= 'a' && txt.charAt(i) <= 'z')
			|| (txt.charAt(i) >= '0' && txt.charAt(i) <= '9')
			|| (txt.charAt(i) == ' ')
			|| (txt.charAt(i) == '?')
			|| (txt.charAt(i) == '?')
		    ))
			return false;
	}
	return true;
}
/**********************************************
*isValid
*
*Verifica que <txt> no contenga simbolos que no sean (A-Z) (a-z) (0-9) (_ .)
**********************************************/
function checkSymbols(txt)
{
	for (var i=0; i<txt.length; i++){
		if (!((txt.charAt(i) >= 'A' && txt.charAt(i) <= 'Z')
			|| (txt.charAt(i) >= 'a' && txt.charAt(i) <= 'z')
			|| (txt.charAt(i) >= '0' && txt.charAt(i) <= '9')
			|| (txt.charAt(i) == '.')
			|| (txt.charAt(i) == '_')
			|| (txt.charAt(i) == '?')
			|| (txt.charAt(i) == '?')
		    ))
			return false;
	}
	return true;
}
/**********************************************
*checkDate
*
*	Verifica que la fecha sea valida
**********************************************/
function checkDate(d, m, a)
{	if(d.length == 2 && d.charAt(0) == 0){
		d = d.charAt(1);
	}
	if (m.length == 2 && m.charAt(0) == 0){
	    m = m.charAt(1); 
	}
	var fecha = new Date(a, m-1, d);
	if (fecha.getDate() == parseInt(d) && fecha.getMonth() == parseInt(m)-1 && fecha.getFullYear() == parseInt(a))
		return true;
	else
		return false;
}
/*****************************************************
*checkTextDate(date,sep,pattern)
* patterns : dd<sep>mm<sep>yyyy y mm<sep>dd<sep>yyyy
*	Verifica que la fecha sea valida
*****************************************************/
function checkTextDate(date,sep,pattern){
	var first,tmp,second,third;
	first = date.substring(0,date.indexOf(sep));
	tmp = date.substring(date.indexOf(sep) + 1,date.length);
	second = tmp.substring(0,tmp.indexOf(sep));
	third = tmp.substring(tmp.indexOf(sep) + 1,tmp.length);
	if(pattern=="dd" + sep + "mm" + sep + "yyyy"){
		d = first;
		m = second;
		y = third;
	}else{
		if(pattern=="mm" + sep + "dd" + sep + "yyyy"){
			m = first;
			d = second;
			y = third;
		}
	}
	return checkDate(d,m,y);
}


/**********************************************
*checkDecimal05
*
*	Verifica que el valor sea entero o
*       decimal terminado en .0 o .5
**********************************************/
function checkDecimal05(valor){
	var r = new RegExp("^[0-9]+(\\.(0|5))?$");
	return (r.test(valor));
}

/**********************************************
*checkDecimal
*
*	Verifica que el valor sea entero o
*       decimal
**********************************************/
function checkDecimal(valor){
	var r = new RegExp("^[0-9]+(\\.[0-9]*)$");
	return (r.test(valor));
}

/**********************************************
*checkAllTextFields
*
*	Verifica todos los [INPUT type=Text] del form <frm>
**********************************************/
function checkAllTextFields(frm)
{
	for (var i=0; i<frm.elements.length; i++){
		if (frm.elements[i].type == "text"){
			if (! checkText(frm.elements[i].value)){
				return false;
			}
		}
	}
	return true;
}

/**********************************************
*detectBrowser
*
*	Devuelve "N" para Netscape Nav. y "M" para MSIE
*
*	Ta bastante fea!!!
*********************************************/
function detectBrowserx()
{
	if (navigator.appName.indexOf("Netscape") > -1)
		return "N";
	else if (navigator.appName.indexOf("Microsoft") > -1)
		return "M";
	else
		return "X";
}

/**********************************************
*addParameter
*
*	Agrega el parametro <param> a la lista <lista>
*
*	Salida de la forma "?param1&param2&param3"
**********************************************/
function addParameter(lista, param)
{
	var ret = "" + lista;
	if (lista.length == 0)
		ret += "?";
	else
		ret += "&";
	ret += param;
	return ret;
}
/**********************************************
*soloNumero
*
*	Verifica que <numero>, sea de tipo numerico
*
**********************************************/
function soloNumero( numero )
{
      var nuevoNumero = new String( numero ) ;
      for ( i = 0 ; i < nuevoNumero.length ; i++ )
          if ( isNaN( parseInt( nuevoNumero.substring( i, i + 1  ) ))) return ( false );
      return ( true ) ;
}
function roundit(Num, Places) {
  if (Places > 0) {
     if ((Num.toString().length - Num.toString().lastIndexOf('.')) > (Places + 1)) {
        var Rounder = Math.pow(10, Places);
        return Math.round(Num * Rounder) / Rounder;
     }
     else return Num;
  }
  else return Math.round(Num);
}
/**********************************************
*validEmail
*
*	Verifica que la direccion de mail
*   este correctamente formada.
**********************************************/
function validEmail(_mail){
	var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9])+$/;
	if (!filter.test(_mail)){
		//alert("Ha ingresado una direcci?n de email incorrecta."); /*CSerra --> para que no muestre el alert*/
		return (false);
	}
	return (true);
}

function soloNumeroDecimalSinMensaje( numero )
{
	var  ptos  ;
	var  resultado ;
	var  hayPunto ;
	var  hayMenos ;
	var  hayNumero ;
	var  hayNumeroDespuesDeMenos ;
	var  hayNumeroDespuesDePunto ;
	hayPunto = false ;
	hayMenos = false ;
	hayNumero  = false ;
	hayNumeroDespuesDeMenos = false ;
	hayNumeroDespuesDePunto = false ;
	ptos = 0 ;
	resultado = true ;
	var nuevoNumero = new String( numero ) ;
	nuevoNumero = trimAll(nuevoNumero);
	if ( nuevoNumero.substring(0,1) =='-' )
	{
		hayMenos = true ;
		nuevoNumero = nuevoNumero.substring(1);
	}
	for ( i = 0 ; i < nuevoNumero.length ; i++ )
		if ( isNaN( parseInt( nuevoNumero.substring( i, i + 1  ) )))
		{
			if ( nuevoNumero.substring( i, i + 1  ) == '.'  && hayNumero )
			{
				ptos = ptos + 1 ;
				hayPunto = true  ;
				if ( ptos > 1  )
				{
					resultado = false ;
					return ( resultado ) ;
				}
			}
			else
			{
				resultado = false ;
				return ( resultado );
			}
		} // Fin si no es nan
		else
		{
			hayNumero = true ;
			hayNumeroDespuesDeMenos = hayMenos ;
			hayNumeroDespuesDePunto = hayPunto ;
		}

	if ( hayMenos  &&  ! hayNumeroDespuesDeMenos )
	{
		resultado = false ;
		return ( resultado );
	}

	if ( ! hayNumeroDespuesDePunto && hayPunto   )
	{
		resultado = false ;
		return ( resultado );
	}
return ( resultado ) ;
}
function trimAll( palabra )
{
   var nuevaPalabra = new String( palabra );
   var ant  , pos  ;
   while( nuevaPalabra.indexOf(' ') != -1 )
   {
      ant = nuevaPalabra.substring( 0 , nuevaPalabra.indexOf(' ')  ) ;
      pos = nuevaPalabra.substring(  nuevaPalabra.indexOf(' ') + 1   , nuevaPalabra.length  )    ;
      nuevaPalabra =  new String ( ant + pos );
   }
  return ( nuevaPalabra )   ;
 }
/**********************************************
*checkNumberFinal
*
*	Verifica que el ultimo caracter de <txt> sea numerico (positivo)
**********************************************/
function checkNumberFinal(txt)
{
    var flag = true;
    if (txt.charAt(txt.length-1) < '0' || txt.charAt(txt.length-1) > '9'){
      flag = false;
    }
    return flag;
}

/**********************************************
*SoloNumeros
*
*	Toma un string <txt> y solo devuelve un
*       string numerico (positivo) eliminado los
*       caracteres que halla en <txt>
**********************************************/
function SoloNumeros(txt)
{
    var txtAux = "";
    for (var i=0; i<txt.length; i++){
      if (!(txt.charAt(i) < '0' || txt.charAt(i) > '9')){
        txtAux = txtAux + txt.charAt(i);
      }
    }
    return txtAux;
}

/**********************************************
*dateAdd
*	El parametro fecha debe ser de tipo Date.
*	toma la cantidad de dias (debe ser numerico) que se quieren 
*   restar o sumar a una fecha, y devuelve la fecha
*   obtenida. Si restaSuma es true, se resta;
*	y si es false, se suma.
**********************************************/
function dateAdd(fecha,dias,restaSuma)
   {  
      //var fechaactual = new Date();
      var milisegfa = fecha.getTime();
	  var diasrestar = parseInt((dias) * (24 * 60 * 60 * 1000));
	  if (restaSuma){
		  var resta = milisegfa - diasrestar;
	  } else {
		  var resta = milisegfa + diasrestar;
	  }
	  var fechaObtenida = new Date(resta);
   	  return fechaObtenida;
   }

/**********************************************
*ultimoDia
*
*	Se obtiene el ultimo dia del mes ingresado.
*   Se tiene en cuenta si el a?o es 
*   bisiesto o no.
**********************************************/
function ultimoDia(mes,anio){
  ultimo_dia=28;
  while (checkDate(ultimo_dia + 1,mes,anio)){
       ultimo_dia++;
  }
  return ultimo_dia;
}

/**********************************************
*formatoFecha
*
*	Devuelve la fecha segun el formato ingresado en el 
*	parametro strFormatoSalida. En strFormato se indica
*	el formato que tiene la fecha pasada en el parametro
*	strFecha. Ejm: strFecha:22/11/2006 (debe ser string); 
*	strFormato: 'dd/mm/yyyy'; strFormatoSalida: 'mm/dd/yyyy'
**********************************************/
function formatoFecha(strFecha,strFormato,strFormatoSalida){
strFormato=strFormato.toLowerCase();
strFormatoSalida=strFormatoSalida.toLowerCase();
var dia = '';
var mes = '';
var anio = '';

//Obtengo el separador
var sepEntrada = getFirstCharNonNumeric(strFecha);
var sepSalida = getFirstCharNonAlphabetic(strFormatoSalida);

//Divido
splFecha=strFecha.split(sepEntrada);
splFormato=strFormato.split(sepEntrada);
splFormatoSalida=strFormatoSalida.split(sepSalida);
strFechaSalida='';

//Comprueba el orden en el que llegan los datos
switch(splFormato[0]){
   case 'dd':
      switch(splFormato[1]){
         case 'mm':
            dia=splFecha[0];
            mes=splFecha[1];
            anio=splFecha[2];
         break;
         case 'yyyy':
         case 'yy':
            dia=splFecha[0];
            mes=splFecha[2];
            anio=splFecha[1];
         break;
      }
   break;
   case 'mm':
      switch(splFormato[1]){
         case 'dd':
            dia=splFecha[1];
            mes=splFecha[0];
            anio=splFecha[2];
         break;
         case 'yyyy':
         case 'yy':
            dia=splFecha[0];
            mes=splFecha[2];
            anio=splFecha[1];
         break
      }
   break;
   case 'yyyy':
   case 'yy':
      switch(splFormato[1]){
         case 'dd':
            dia=splFecha[1];
            mes=splFecha[2];
            anio=splFecha[0];
         break;
         case 'mm':
            dia=splFecha[2];
            mes=splFecha[1];
            anio=splFecha[0];
         break;
      }
   break;
}
//Arma la fecha de salida
switch(splFormatoSalida[0]){
   case 'dd':
      switch(splFormatoSalida[1]){
         case('mm'):
               strFechaSalida=dia+sepSalida+mes+sepSalida+anio;
         break;
         case 'yyyy':
         case 'yy':
               strFechaSalida=dia+sepSalida+anio+sepSalida+mes;
         break;
      }
   break;
   case 'mm':
      switch(splFormatoSalida[1]){
         case 'dd':
            strFechaSalida=mes+sepSalida+dia+sepSalida+anio;
         break;
         case 'yyyy':
         case 'yy':
            strFechaSalida=mes+sepSalida+anio+sepSalida+dia;
         break;
      }
   break;
   case 'yyyy':
   case 'yy':
      switch(splFormatoSalida[1]){
         case 'dd':
            strFechaSalida=anio+sepSalida+dia+sepSalida+mes;
         break;
         case 'mm':
            strFechaSalida=anio+sepSalida+mes+sepSalida+dia;
         break;
      }
   break;
}
return strFechaSalida;
}

/**********************************************
*Funcion getFirstCharNonNumeric
*	 Permite obtener el primer caracter de la cadena 
* 	que se pasa como parametro que es NO numerico.*
************************************************/
function getFirstCharNonNumeric(strFecha){

	for (i=0;i<strFecha.length;i++){
        if (strFecha.charAt(i) < '0' || strFecha.charAt(i) > '9'){
                 break;
        }
	}
	 return strFecha.charAt(i);
}

/**********************************************
*Funcion getFirstCharNonAlphabetic
*	Permite obtener el primer caracter de la cadena 
* 	que se pasa como parametro que es NO alfabetico.*
************************************************/
function getFirstCharNonAlphabetic(strFormatoSalida){

	for (i=0;i<strFormatoSalida.length;i++){
         if (strFormatoSalida.charAt(i) < 'a' || strFormatoSalida.charAt(i) > 'z'){
	         break;
         }
	}
	return strFormatoSalida.charAt(i);
}

/**********************************************
*Funcion compararFechas
*	Permite comparar dos fechas ingresadas
*	como parametro. Las mismas deben ser DATE.
*	el parametro bflagfecha es un boolean y si es true, se compara
*	teniendo en cuenta la hora, si es false solamente se compara la fecha (dia, mes, a?o).
************************************************/
function compararFechas(fecha1,fecha2,bflagfecha){
var fec1;
var fec2;
	if (bflagfecha){
		fec1 = fecha1;
		fec2 = fecha2;
	} else {
		fec1 = new Date(fecha1.getFullYear(),fecha1.getMonth(),fecha1.getDate());
		fec2 = new Date(fecha2.getFullYear(),fecha2.getMonth(),fecha2.getDate());
	}
	if (fec1 < fec2){
		return -1;
	} else {
		if (fec1 > fec2){
			return 1;
		} else {
			return 0;
		}
	}
}


