

function redondear(cantidad, decimales) 
{
var cantidad = parseFloat(cantidad);
var decimales = parseFloat(decimales);
//decimales = (!decimales ? 2 : decimales);
return Math.round(cantidad * Math.pow(10, decimales)) / Math.pow(10, decimales);
} 

function IsNumeric(sText)
{ 
    var ValidChars = "0123456789"; 
    var Char;
    for (i = 0; i < sText.length; i++)
    {
       Char = sText.charAt(i);
       if (ValidChars.indexOf(Char) == -1)
        {
    //        alert('El dato debe ser numerico')
          return false;
       }
    }
    //return IsNumeric;
    return true;
}

function validar_ok(obj,req,tipo)
{
    alert (obj.value);
}



function validar(obj,req,tipo)
{

/*
objeto: el objeto que se desea validar
req: Si es requerido (1) o no (0)
tipo: El tipo de dato, puede ser :
				texto
				numero
				hora
				minuto
				Uti
				combo (para que el value no sea 0)
				emp (como minimo 2 hasta 48)

stralert: el mensaje que se mostrara si da error
*/

stralert =''
estado = true
res[1]
		if (obj)
		{
		
					if (tipo=='combo')
					{
								if (req==1)
								{
										if (obj.value =='0')
										{
												stralert = stralert + obj.name + ' Es un campo Requerido'+ '\n'
												estado = false
										}
								}		
					}

					
					if (tipo=='numero')
					{
								if (req==1)
								{
										if (obj.value =='')
										{
												stralert = stralert + obj.name + ' Es un campo Requerido'+ '\n'
												estado = false
										}
										else 
										{
												if (!(IsNumeric(obj.value)))
												{
												stralert = stralert + obj.name + ' Es un campo Numérico'+ '\n'
												estado = false
												}
										}
								}		
								else		
								{																									
											if (obj.value !='')
											{
													if (!(IsNumeric(obj.value)))
													{
													stralert = stralert + obj.name + ' Es un campo Numérico'+ '\n'
													estado = false
													}
											}		
								}
					}


					if (tipo=='texto')
					{
								if (req==1)
								{
										if (obj.value =='')
										{
												stralert = stralert + obj.name + ' Es un campo Requerido'+ '\n'
												estado = false
										}
								}
					}



					if (tipo=='hora')
					{
								if (req==1)
								{
										if (obj.value =='')
										{
												stralert = stralert + obj.name + ' Es un campo Requerido'+ '\n'
												estado = false
										}
										else 
										{
											if (!((obj.value >= 0 ) && (obj.value < 24) && (IsNumeric(obj.value))))
											{
											stralert = stralert + obj.name + ' Es un campo de Hora'+ '\n'
											estado = false
											}
										}
								}
	
								else		
								{																									
											if (obj.value !='')
											{
												if (!((obj.value >= 0 ) && (obj.value < 24) && (IsNumeric(obj.value))))
														{
														stralert = stralert + obj.name + ' Es un campo de Hora'+ '\n'
														estado = false
														}
											}		
								}
					}



					if (tipo=='minuto')
					{
								if (req==1)
								{
										if (obj.value =='')
										{
												stralert = stralert + obj.name + ' Es un campo Requerido'+ '\n'
												estado = false
										}
										else 
										{
											if (!((obj.value >= 0 ) && (obj.value < 60) && (IsNumeric(obj.value))))
													{
													stralert = stralert + obj.name + ' Es un campo de Minuto'+ '\n'
													estado = false
													}
												
										}
								}
								else		
								{																									
											if (obj.value !='')
											{
											if (!((obj.value >= 0 ) && (obj.value < 60) && (IsNumeric(obj.value))))
													{
													stralert = stralert + obj.name + ' Es un campo de Minuto'+ '\n'
													estado = false
													}
											}		
								}

					if (tipo=='uti')
					{
								if (req==1)
								{
										if (obj.value =='')
										{
												stralert = stralert + obj.name + ' Es un campo Requerido'+ '\n'
												estado = false
										}
										else 
										{
											if (!((obj.value >= 0 ) && (obj.value <= 100) && (IsNumeric(obj.value))))
													{
													stralert = stralert + obj.name + ' Es un campo para Utis (numerico y menor o igual que 100 ' + '\n'
													estado = false
													}
										}
								}
	
								else		
								{																									

											if (obj.value =!'')
											{
												if (!((obj.value >= 0 ) && (obj.value <= 100) && (IsNumeric(obj.value))))
														{
														stralert = stralert + obj.name + ' Es un campo para Utis (numerico y menor o igual que 100 ' + '\n';
														estado = false;
														}
											}		

								}

					}

					

		}
					
		}
		else
		{
		stralert = stralert + 'No se ha encontrado el Objeto ' + obj + '\n';
		estado = false;
		}
		
		res[0] = estado
		res[1] = stralert
		return res;
}

/**
 * DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=2005;
var maxYear=2009;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
//	var strMonth=dtStr.substring(0,pos1)
//	var strDay=dtStr.substring(pos1+1,pos2)
	var strDay=dtStr.substring(0,pos1)
	var strMonth=dtStr.substring(pos1+1,pos2)
	
	
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
	//	alert("The date format should be : mm/dd/yyyy")
		alert("El formato debe ser : dd/mm/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Por Favor Ingrese un Mes Válido")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Por Favor Ingrese un Día Válido")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
//		alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		alert("Ingrese un Año entre "+minYear+" y "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("Por Favor Ingrese un Año Válido")
		return false
	}
return true
}

function ValidateForm(){
	//var dt=document.frmSample.txtDate
	var dt = document.M.fecha
//	alert (dt.value)
//	return false

	if (isDate(dt.value)==false)
	{
		dt.focus()
		return false
		estado=false;
	}
    return true
 }

function ValidarFecha(dt){
	//var dt=document.frmSample.txtDate
//	var dt = document.M.fecha
//	alert (dt.value)
//	return false


	if (isDate(dt.value)==false)
	{
		dt.focus()
		return false
		estado=false;
	}
    return true
 }

function ValidarFechaCompleta (str)
{
	str = trimAll(str)
	var arrTimeStr = str.split(" ");
	
	
	if (arrTimeStr[0] || arrTimeStr[0]!= '')
		{
			estado = ValidarFechastr(arrTimeStr[0]);
				if (estado)
				{
						if (arrTimeStr.length >= 2)
						{
							//alert(arrTimeStr[1])
							estado = ValidarTiempo(arrTimeStr[1]);
						}
				}
				else
				{
					estado = false;
				}
		}
		else
		{
		estado = false;
		}
	
//	alert (arrTimeStr.length)
	
	if (estado)
	{
		if (arrTimeStr.length > 2)
		{
				alert ('Por favor ingese sólo un valor de fecha y hora compatible (dd/mm/aaaa hh:mm o dd/mm/aaaa)')
				estado= false
		}
	}	
			 
	if (estado)
	{
		return true
	}		 
	else
	{
		return false
	}
}

function ValidarFechastr(strdt){
	
	if (isDate(strdt)==false)
	{
		//dt.focus()
		return false
		estado=false;
	}
    return true
}
 
 
function ValidarTiempo(timeStr) {
// Checks if time is in HH:MM:SS AM/PM format.
// The seconds and AM/PM are optional.



var timePat = /^(\d{1,2}):(\d{2})(:(\d{2}))?(\s?(AM|am|PM|pm))?$/;

	var matchArray = timeStr.match(timePat);
	if (matchArray == null) {
		alert("El tiempo no tine un formato válido.(dd:mm)");
		return false;
	}
	
	hour = matchArray[1];
	minute = matchArray[2];
	second = matchArray[4];
	ampm = matchArray[6];

	if (second=="") { second = null; }
	if (ampm=="") { ampm = null }

	if (hour < 0  || hour > 23) {
		alert("El valor de Hora debe estar entre 0 y 23.");
		return false;
	}
	//if (hour <= 12 && ampm == null) {
	//	if (confirm("Indique formato de horas utilizado.  OK = 12hs, CANCEL = 24hs")) {
	//		alert("Debe especificar AM o PM.");
	//	return false;
	//	}
	//}
	//if  (hour > 12 && ampm != null) {
	//	alert("No es necesario especificar AM o PM para formato de 24hs.");
	//	return false;
	//}
	
	if (minute<0 || minute > 59) {
		alert ("El valor de Minuto debe estar entre 0 y 59.");
		return false;
	}
	if (second != null && (second < 0 || second > 59)) {
		alert ("El valor de Segundos debe estar entre 0 y 59.");
		return false;
	}
	return true;

}



function RecorrerCheckbox()
{
			var oChk, i;			
			var Seleccionadas;
			var Todas;
			Seleccionadas = "";
			Todas = "";
			
			oChk = document.getElementsByTagName('input');
			// Recorro todos los elementos 'input' buscando solo los que sean de tipo 'checkbox'
			// y de estos, solo los seleccionados 
			i = 0;
			while (i < oChk.length)
			{
				if (oChk[i].type == "checkbox")
				{
						if (oChk[i].name != "SelectAll")
						{
								Todas = Todas + oChk[i].value + "|";
								// Si esta seleccionado, lo agrego a un string
								if (oChk[i].checked)
								{
									Seleccionadas = Seleccionadas + oChk[i].value + "|";
								}
						}
				}
				i++;
			}
			// Le quito el ultimo pipe que queda al final del string.
			Todas = Todas.substr(0, Todas.length-1);
			Seleccionadas = Seleccionadas.substr(0, Seleccionadas.length-1);

			resultado= new Array;
			resultado [0]= Todas;
			resultado [1]= Seleccionadas;
			return resultado;
}

		function FormatoAnsiCompleto(var1)
		{
		dd = var1.substr(0,2);
		mm = var1.substr(3,2);
		yyyy = var1.substr(6,4);
		ansi = yyyy + mm + dd;
		return ansi;
		
		}

		function EsMayor(var1,var2)
		{
		resultado= new Array;
		var1= parseInt(var1);
		var2= parseInt(var2);
		
		if (var1 <= var2)
				{
				resultado [0]= true;
				resultado [1]= '';
				}
		else
				{
				resultado [0]= false;
				resultado [1]= 'La Fecha Desde es Mayor que la fecha Hasta';
				}
		return resultado;
		}



function leftTrim(sString)
{
	while (sString.substring(0,1) == ' ')
	{
		sString = sString.substring(1, sString.length);
	}
	return sString;
}


function rightTrim(sString)
{
	while (sString.substring(sString.length-1, sString.length) == ' ')
	{
		sString = sString.substring(0,sString.length-1);
	}
	return sString;
}



function trimAll(sString)
{
	while (sString.substring(0,1) == ' ')
	{
		sString = sString.substring(1, sString.length);
	}
		while (sString.substring(sString.length-1, sString.length) == ' ')
	{
		sString = sString.substring(0,sString.length-1);
	}
	return sString;
}