//===========================================================================================
//===== Módulo: Funciones Validaciones en Javascript                                    =====
//===== Requerimientos: Javascript 1.1                                                  =====
//===== Autor: Diego Toscano (dtoscano@ciudad.com.ar)                                   =====
//===== Fecha: Febrero 2002                                                             =====
//===== Instrucciones: Poner esta página como include (invocarla con <script src="...") =====
//===========================================================================================

//=====================================================================
// FUNCIONES:
//
// STRINGS:
// ltrim(theString)
// rtrim(theString)
// trim(theString)
// strReplace(theString, theStringSource, theStringTarget)
// inStr(sString1, sString2)
//
// FECHAS:
// getDateToStr(pdDate, psDateDestinationFormat)
// toStrDateFormat(psDate, psDateSourceFormat, psDateDestinationFormat)
// dayDiff(psYyyyMmDd1, psYyyyMmDd2)
// isDateTime(psDateDDMMYYYY)	// dd/mm/yyyy hh:mm:ss
// isDate(psDateDDMMYYYY)	// dd/mm/yyyy or dd-mm-yyyy
// isTime(psTimeHHMMSS)		// hh:mm:ss
//
// VALIDACIONES:
// caract(s)
// esVacio(s)
// noEsNumero(n)
// esNumeroDecimal(pValor, pEnteros, pDecimales)
// esBlanco(s)
// noTieneDatos(s)
// estaCaracterEnTexto(s, texto)
// estaEnRangoCaracter(s, iMin, iMax)
// estaEnRangoNumerico(s, iMin, iMax)
// esEmail(s)
// esLogin(s)
// esCadenaNumerica(s)
// esCadenaAlfanumerica(s)
// esCadenaASCII(s)
// 
// RADIOS Y COMBOS:
// comboSeleccionado(nombre)
// comboMultipleSeleccionado(nombre)
// radioSeleccionado(nombre)
// checkSeleccionado(nombre, cantidad)
// 
//=====================================================================


//=====================================================================
// *  FUNCIONES "TRIM"  *
//=====================================================================
// ------  Remuevo espacios al inicio del string (left)  ------
//=====================================================================
function ltrim(theString) 
{
	var i = 0;
	while ((theString.substring(i, i + 1) == " ") && (i < theString.length))
		i++;
	return theString.substr(i);
}

//=====================================================================
// ------  Remuevo espacios al final del string (right)  ------
//=====================================================================
function rtrim(theString) 
{
	var i = theString.length - 1;
	while ((theString.substring(i, i + 1) == " ") && (i >= 0))
		i--;
	return theString.substr(0, i + 1);
}

//=====================================================================
// ------  Remuevo espacios al inicio y al final del string  ------
//=====================================================================
function trim(theString) 
{
	return ltrim(rtrim(theString));
}

//=====================================================================
// ------  Reemplazo cadena de texto por otro dentro de string   ------
//=====================================================================
function strReplace(theString, theStringSource, theStringTarget) 
{
	var i = 0;
	var s = theString;
	
	if (theStringSource.length != 0)
	{
		while (i < s.length)
		{
			while ((s.substring(i, i + theStringSource.length) != theStringSource) && (i < s.length + theStringSource.length))
				i++;
			if (i < s.length-1)
				s = s.substr(0,i) + theStringTarget + s.substr(i + theStringSource.length, s.length-1 );
		}
	}
	return (s);
}

//=====================================================================
// ------  Si está caracter en texto, pone el nro de posición    ------
//=====================================================================
function inStr(sString1, sString2)
{
	var i = 0;
	
	if ( (sString1 == null) || (sString2 == null) )
		return (null);
	if (sString1.length < sString2.length)
		return (0);
	if ( (sString1.length == 0) || (sString2.length == 0) )
		return (0);
	while ((sString1.substring(i, i + sString2.length) != sString2) && (i < sString1.length + sString2.length))
		i++;
	if (i < sString1.length-1)
		return (i+1);
	else
		return (0);
}


//=====================================================================
// *   F E C H A S   *
//=====================================================================
// ------  Convierte una fecha real a un formato str de fecha  ------
//=====================================================================
function getDateToStr(pdDate, psDateDestinationFormat)
{
	// (Params = pdDate: Date(); psDateDestinationFormat: {'dmy','mdy','ymd'})
	var sDateSource, sDateDestination;
	sDateSource = (pdDate.getMonth() + 1) + '/';
	sDateSource += pdDate.getDate() + '/';
	sDateSource += pdDate.getYear();
	sDateDestination = toStrDateFormat(sDateSource, 'mdy', psDateDestinationFormat);
	return (sDateDestination);
}

//=====================================================================
// --  Convierte un formato str de fecha a otro formato str de fecha --
//=====================================================================
function toStrDateFormat(psDate, psDateSourceFormat, psDateDestinationFormat)
{
	var sDateS = psDate;
	var vDateS = psDate.split('/');
	var sDateD;
	var iYearS, iMonthS, iDayS;
	switch(psDateSourceFormat)
	{
		case 'ymd':
			iYearS	= 0;
			iMonthS	= 1;
			iDayS	= 2;
			break;
		case 'dmy':
			iYearS	= 2;
			iMonthS	= 1;
			iDayS	= 0;
			break;
		case 'mdy':
			iYearS	= 2;
			iMonthS	= 0;
			iDayS	= 1;
			break;
		default:
			iYearS	= 0;
			iMonthS	= 1;
			iDayS	= 2;
	}
	switch(psDateDestinationFormat)
	{
		case 'ymd':
			sDateD = vDateS[iYearS] + '/' + vDateS[iMonthS] + '/' + vDateS[iDayS];
			break;
		case 'dmy':
			sDateD = vDateS[iDayS] + '/' + vDateS[iMonthS] + '/' + vDateS[iYearS];
			break;
		case 'mdy':
			sDateD = vDateS[iMonthS] + '/' + vDateS[iDayS] + '/' + vDateS[iYearS];
			break;
		default:
			sDateD = vDateS[iYearS] + '/' + vDateS[iMonthS] + '/' + vDateS[iDayS];
	}
	return (sDateD);
}

//=====================================================================
// --  Resta string Fecha2 con Fecha1 y el resultado es en Dias  --
//=====================================================================
function dayDiff(psYyyyMmDd1, psYyyyMmDd2)
{
	var dFecha1, dFecha2, iRestaDias;
	var MinMilli = 1000 * 60;
	var HrMilli = MinMilli * 60;
	var DyMilli = HrMilli * 24;
	dFecha1 = new Date(psYyyyMmDd1);
	dFecha2 = new Date(psYyyyMmDd2);
	iRestaDias = Math.round((dFecha2 - dFecha1) / DyMilli);
	if (inStr(navigator.appName, 'Netscape') > 0)
	{
		iRestaDias = iRestaDias + 693961;
	}
	return (iRestaDias);

}

//=====================================================================
// ---  Verifica si es Fecha Válida (formato string en dd/mm/yyyy)  ---
//=====================================================================
function isDate(psDateDDMMYYYY) {
	var bResult = false;
	var vDate;
	vDate = psDateDDMMYYYY.split('/');
	// si no hay elementos
	if (typeof(vDate[1]) == 'undefined')
		vDate = psDateDDMMYYYY.split('-');
	var myDate = new Date(parseInt(vDate[2],10), parseInt(vDate[1],10)-1, parseInt(vDate[0],10));
	if ( (myDate.getMonth()+1) == parseInt(vDate[1],10) )
		bResult = true;
	return(bResult); 
}

//=====================================================================
// ---  Verifica si es Hora Válida (formato string en hh:mm:ss)  ---
//=====================================================================
function isTime(psTimeHHMMSS) {
	var vTime = psTimeHHMMSS.split(':');
	// horas
	if (!estaEnRangoNumerico(vTime[0], 0, 23))	{
		return false;
	}
	// minutos
	if (!estaEnRangoNumerico(vTime[1], 0, 59))	{
		return false;
	}
	// segundos
	// si no hay elementos
	if (typeof(vTime[2]) != 'undefined')	{
		if (!estaEnRangoNumerico(vTime[2], 0, 59))	{
			return false;
		}
	}
	return true; 
}

//=====================================================================
// ---  Valida Fecha y Hora (formato string en dd/mm/yyyy hh:mm:ss)  ---
//=====================================================================
function isDateTime(datetime)	{
	var vDateTime = datetime.split(' ');
	// fecha
	if (!isDate(vDateTime[0]))	{
		return false;
	}
	// hora
		// si no hay elementos
	if (typeof(vDateTime[1]) == 'undefined')
		return false;
	if (!isTime(vDateTime[1]))	{
		return false;
	}
	return true;
}

//=====================================================================
// *  FUNCIONES PARA VALIDAR CADENA DE CARACTERES  *
//=====================================================================
var whitespace = " \t\n\r";
var alphaChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
var digitChars = "0123456789";
var asciiChars = alphaChars + digitChars + "!\"#$%&'()*+,-./:;<=>?@[\]^_`{}~";

//=====================================================================
// ------  Retorno el total de caracteres del mensaje  ------
//=====================================================================
function caract(s)
{
	caracteres = s.length;
	return caracteres;
}

//=====================================================================
// ------  Retorno booleano si el parámetro es vacío  ------
//=====================================================================
function esVacio(s)
{
	return ((s == null) || (s.length == 0))
}

//=====================================================================
// ------  Retorno booleano si el parámetro no es numérico  ------
//=====================================================================
function noEsNumero(n)
{
    return (isNaN(n))
}

//=====================================================================
// ------  Retorno booleano si el parámetro es numérico decimal  ------
//=====================================================================
function esNumeroDecimal(pValor, pEnteros, pDecimales)
{

	if (isNaN(pValor))
		return false;
	var cantInt, cantDec;
	var ElPunto	= pValor.indexOf('.');
	if ( ElPunto == -1 )	{
		cantInt = pValor.length;
		cantDec = 0;	}
	else	{
		cantInt = ElPunto;
		cantDec = (pValor.length)-ElPunto-1;	}
	if ( cantInt > pEnteros )	
		return false;
	if ( cantDec > pDecimales )	
		return false;
	return true;
}

//=====================================================================
// ---  Retorno booleano si el parámetro tiene espacios en blanco  ---
//=====================================================================
function esBlanco(s)
{   
	var i;
	if (esVacio(s)) return true;
	for (i = 0; i < s.length; i++)
	{
		var c = s.charAt(i);
		if (whitespace.indexOf(c) == -1) return false;
	}
	return true;
}

//=====================================================================
// ------  Valido si el parámetro está vacío o si tiene blancos  ------
//=====================================================================
function noTieneDatos(s)
{
	if (esVacio(s) || esBlanco(s)) return true;
	return false;
}

//=====================================================================
// ------  Valido si hay un determinado caracter en una cadena  ------
//=====================================================================
function estaCaracterEnTexto(s, texto)
{  
    var i;
    for (i = 0; i < texto.length; i++)
    {   
        var c = texto.charAt(i);
        if (s.indexOf(c) == -1) return false;
    }
    return true;
}

//=====================================================================
// -- Valido si la Cant. de Caracteres está fuera de un rango establecido --
// Entrada: s=string; iMin,iMax=cant mínima y máxima de caracteres.
// Restricción: iMax >= iMin
//=====================================================================
function estaEnRangoCaracter (s, iMin, iMax)
{  
	if ( (noEsNumero(iMin)) || (noEsNumero(iMax)) )
		return false;
	if (iMin > iMax)
		return false;
	if ( (caract(s) < iMin) || (caract(s) > iMax) )
		return false;
    return true;
}

//=====================================================================
// -----   Valido que "s" sea >= a iMin y <= iMax   -----
// Entrada: s=string; iMin,iMax = Nros mínimo y máximo del rango.
// Restricción: iMax >= iMin
//=====================================================================
function estaEnRangoNumerico(s, iMin, iMax)
{  
	if ( (noEsNumero(s)) || (noEsNumero(iMin)) || (noEsNumero(iMax)) )
		return false;
	if (iMin > iMax)
		return false;
	if ( (s < iMin) || (s > iMax) )
		return false;
    return true;
}

//=====================================================================
// --- Valido si el parámetro se puede considerar un E-MAIL válido ---
//=====================================================================
function esEmail(s)
{
	if (esVacio(s)) return false;
	// es s un espacio en blanco?
	if (esBlanco(s)) return false;
	// debe haber algún caracter antes de la @
	// por lo que comenzamos a buscar en el 1er. caracter
	var i = 1;
	var sLength = s.length;
	// buscamos @
	while ((i < sLength) && (s.charAt(i) != "@"))
		{ i++ }
	if ((i >= sLength) || (s.charAt(i) != "@")) return false;
	else i += 2;
	// buscamos .
	while ((i < sLength) && (s.charAt(i) != "."))
		{ i++ }
	// debe haber al menos 1 caracter después del .
	if ((i >= sLength - 1) || (s.charAt(i) != ".")) return false;
	else return true;
}

//=====================================================================
// --- Valido si el parámetro se puede considerar un LOGIN válido ---
// Valida si "s" contiene "sólo" caracteres: "a..z", "A..Z", "0..9" y "_".
//=====================================================================
function esLogin(s)
{
	if (noTieneDatos(s)) return false;
	var checkOK = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_";
	var checkStr = s;
	var allValid = true;
	var decPoints = 0;
	var allNum = "";
	for (i = 0;  i < checkStr.length;  i++)
	{
		 ch = checkStr.charAt(i);
		 for (j = 0;  j < checkOK.length;  j++)
		   if (ch == checkOK.charAt(j))
		     break;
		 if (j == checkOK.length)
		  {
		    allValid = false;
		    break;
		  }
		 allNum += ch;
	}
	if (!allValid) return false;
	return true;
}

//=====================================================================
// --- Valido si el parámetro es una Cadena de caracteres Numérica ---
// Valida si "s" contiene sólo caracteres: "0..9" (enteros); Sin "," ni "."
//=====================================================================
function esCadenaNumerica(s)
{
	if (noTieneDatos(s)) return false;
	var checkOK = "1234567890";
	var checkStr = s;
	var allValid = true;
	var decPoints = 0;
	var allNum = "";
	for (i = 0;  i < checkStr.length;  i++)
	{
		 ch = checkStr.charAt(i);
		 for (j = 0;  j < checkOK.length;  j++)
		   if (ch == checkOK.charAt(j))
		     break;
		 if (j == checkOK.length)
		  {
		    allValid = false;
		    break;
		  }
		 allNum += ch;
	}
	if (!allValid) return false;
	return true;
}

//=====================================================================
// --- Valido si el parámetro es una Cadena AlfaNumérica ---
//=====================================================================
function esCadenaAlfanumerica(str)	{
	var AlphaNum = alphaChars + digitChars;
	var v_len = str.length;
	var i;
	for (i = 0; i < v_len; i++)	{
		if (AlphaNum.indexOf(str.charAt(i)) == -1)
		return false;
	}
	return true;
}

//=====================================================================
// --- Valido si el parámetro es una Cadena ASCII ---
//=====================================================================
function esCadenaASCII(str)	{
	var v_len = str.length;
	var i;
	for (i = 0; i < v_len; i++)	{
		if (asciiChars.indexOf(str.charAt(i)) == -1)
		return false;
	}
	return true;
}


//=====================================================================
// *  FUNCIONES PARA VALIDAR COMBOS Y RADIOS  *
//=====================================================================

//=====================================================================
// --- Valido que el Combo No tenga el primer ítem seleccionado ---
// (nombre = parámetro pasado por ej. "document.form.nombre_combo")
//=====================================================================
function comboSeleccionado(nombre)
{
	if (nombre.selectedIndex == 0) return false; 
	else return true;
}

//=====================================================================
// --- Valido si COMBO MULTIPLE tiene al menos 1 ítem seleccionado ---
// (nombre = parámetro pasado por ej. "document.form.nombre_combo")
//=====================================================================
function comboMultipleSeleccionado(nombre)
{
	var i;
	var cont = 0;
	for (i = 0; i < nombre.length; i++)
		if (nombre.selectedIndex == i) cont++;
	if (cont == 0) return false;
	else return true;
}

//=====================================================================
// -----  Valido si el Radio tiene al menos un ítem seleccionado  -----
// (nombre = parámetro pasado por ej. "document.form.nombre_radio")
//=====================================================================
function radioSeleccionado(nombre)
{
	var i;
	var cont = 0;
	// si no hay elementos
	if (typeof(nombre) == 'undefined')
		return false;
	// si hay un solo elemento
	else	{
		if (typeof(nombre.length) == 'undefined')	{
			if (nombre.checked) cont++;
		}
		// si hay más de un elemento
		else	{
			for (i = 0; i < nombre.length; i++)
				if (nombre[i].checked) cont++;
		}
	}
	if (cont == 0)
		return false;
	else 
		return true;
}

//=====================================================================
// ---  Valido si los Checkbox tienen al menos un ítem seleccionado ---
// (nombre = parámetro pasado por ej. "document.form.nombre_check")
// (cantidad = parámetro cantidad mínima de items a seleccionar)
//=====================================================================
function checkSeleccionado(nombre, cantidad)
{
	var i;
	var cont = 0;
	// si no hay elementos
	if (typeof(nombre) == 'undefined')
		return false;
	// si hay un solo elemento
	else	{
		if (typeof(nombre.length) == 'undefined')	{
			if (nombre.checked) cont++;
		}
		// si hay más de un elemento
		else	{
			for (i = 0; i < nombre.length; i++)
				if (nombre[i].checked) cont++;
		}
	}
	if (cont < cantidad)
		return false;
	else 
		return true;
}
