/**
Estas funciones están probadas en browsers Netscape 4.x y Explorer 4.x.
*/
function rtrim(cadena) {
    cadena += "";
    for (var i = cadena.length -1; (i >= 0) && ((cadena.charAt(i) == ' ')); i--)
        ;
    return cadena.substring(0, i+1);
}

function ltrim(cadena) {
    cadena += "";
    for (var i = 0; (i < cadena.length) && ((cadena.charAt(i) == ' ')); i++)
        ;
    if (i == cadena.length) {
        return "";
    }
    return cadena.substring(i);
}

function trim(cadena) {
    return ltrim(rtrim(cadena));
}

/** Las siguientes funciones se utilizan para validar un número de punto flotante. */

var r1Float = new RegExp("(\,\,)|([0-9]{4}\,)|([0-9]{1}\,)|(^[0]{0,}\,)|([\,]+[0-9]{0,2}[\,$])|(\\..*[\\.\,])");
/*var r1Float = new RegExp("(\,\,)|([0-9]{4}\,)|(^[0]{0,}\,)|([\,]+[0-9]{0,2}[\,$])|(\\..*[\\.\,])");*/
var r2Float = new RegExp("(((\\[?)[0-9]\\,[0-9]{3}(\\]?))|(^[0-9]*))(\\.[0-9]+)?$")

function isFloat(number) {
	number = trim(number)
	return (!r1Float.test(number) && r2Float.test(number));
}

/*Esta funcion recibe un float y un rango y lo valida*/
function isFloatRange(number, min, max)  {
	if (!isFloat(number)) {
		return false;
	}
	var theValue = parseFloat(number.split(",").join(""));
	return theValue >= min && theValue <= max
}

var r1Int = new RegExp("(\,\,)|([0-9]{4}\,)|(^[0]{0,}\,)|([\,]+[0-9]{0,2}[\,$])");
var r2Int = new RegExp("((\\[?)[0-9]\\,[0-9]{3}(\\]?)$)|(^[0-9]+)$")

function isInt(number) {
	number = trim(number);
	return (!r1Int.test(number) && r2Int.test(number));
}

/*Esta funcion recibe un entero y un rango y lo valida*/
function isIntRange(number, min, max)  {
	if (!isInt(number)) {
		return false;
	}
	var theValue = parseInt(number.split(",").join(""));
	return theValue >= min && theValue <= max
}


/*Esta funcion valida una hora y retorna falso o verdadero*/
/* Recibe el formato de HH:MM*/
function isTime(time)  {
	var HP
	time = trim(time)
	HP = time.split(":")
	if (HP.length != 2) {
		return false;
	}
	return(HP[0] < 24 && HP[0] >= 0 && HP[1] < 60 && HP[1] >= 0)
}


/*Esta funcion valida una fecha y retorna falso o verdadero*/
/* Recibe el formato de Dia/Mes/Ano*/
function isDateDMY(date)  {
	var FP
	date = trim(date)
	FP = date.split("/")
	if (FP.length != 3) {
		return false
	}
	return isSplitDateDMY(FP[0], FP[1], FP[2])
}


function isSplitDateDMY(day, month, year)  {
	if (!isInt(day) || !isInt(month) || !isInt(year)) {
		return false;
	}
	date = new Date(year, month-1, day)
	return (date.getDate() == day) && ((date.getMonth()+1) == month) && (date.getFullYear() == year);
}


// Retorna si la fecha inferior efectivamente es inferior
// que la fecha superior. La fecha debe encontrarse en formato dd/mm/yyyy
// -1 a < b, 0 a == b, 1 a > b
function compareDatesDMY(a, b) {
	var firstDateArray, secondDateArray;
	firstDateArray = a.split("/");
	secondDateArray = b.split("/");
	aDate = new Date(firstDateArray[2], firstDateArray[1]-1, firstDateArray[0]);
	bDate = new Date(secondDateArray[2], secondDateArray[1]-1, secondDateArray[0]);
	if (aDate.getTime() < bDate.getTime()) {
		return -1;
	}
	if (aDate.getTime() == bDate.getTime()) {
		return 0;
	}
	return 1;
}

function isChecked(field) {
	if (!field) {
		return false;
	}
	if (field.length) {
		for (var i = 0; i < field.length; i++) {
			if (field[i].checked) {
				return true;
			}
		}
		return false;
	}
	return field.checked;
}


/** Valida un email */
function isEmail(str) {
  var r1 = new RegExp("(@.*@)|(\\.\\.)|(@\\.)|(^\\.)");
  var r2 = new RegExp("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$");
  return (!r1.test(str) && r2.test(str));
}


/** Estas son la validaciones en si de las formas */

var _campoError = null;
var _errores    = "";

function appendErrorMessage(msgError) {
    _errores += ((_errores != "") ? "\n":"") + "        " + msgError
}

function appendErrorMessageFocus(campo, msgError) {
    _errores += ((_errores != "") ? "\n":"") + "        " + msgError
    if (_campoError == null) {
                _campoError = campo;
    }
}

function validarLista(lista, msgError, indiceInicial, funcion) {
    if (!indiceInicial && indiceInicial != 0) {
        indiceInicial = 1;
    }
    if (lista.selectedIndex < indiceInicial ||
        (funcion ? !eval("funcion(lista)") : false)) {
        appendErrorMessage(msgError)
        if (_campoError == null) {
            _campoError = lista;
        }
        return false;
    }
    return true;
}

function validarSeleccion(campo, msgError, funcion) {
    if (!isChecked(campo) ||
        (funcion ? !eval("funcion(campo)") : false)) {
        appendErrorMessage(msgError)
        if (_campoError == null) {
            if (campo.length) {
                _campoError = campo[0]
            } else {
                _campoError = campo;
            }
        }
        return false;
    }
    return true;
}

function validarCampo(campo, msgError, longitudMinima, longitudMaxima, funcion) {
    if (!longitudMinima  && longitudMinima != 0) {
        longitudMinima = 1
    }
    if (!longitudMaxima ) {
		longitudMaxima = Number.MAX_VALUE
    }
    var value = trim(campo.value)
    if (value.length < longitudMinima || value.length > longitudMaxima ||
        (funcion ? !eval("funcion(campo)") : false)) {
        appendErrorMessage(msgError)
        if (_campoError == null) {
            _campoError = campo;
        }
        return false;
    }
    return true;
}

function validarCampoOpcional(campo, msgError, longitudMinima, longitudMaxima, funcion) {
	if (trim(campo.value).length > 0) {
		return validarCampo(campo, msgError, longitudMinima, longitudMaxima, funcion)
	}
}

function validarFecha(dia, mes, ano, msgError, funcion) {
	 if (!isIntRange(dia.value, 1, 31)) {
        appendErrorMessage(msgError)
        if (_campoError == null) {
            _campoError = dia;
        }
        return false;
	}
    if (mes.selectedIndex < 1) {
        appendErrorMessage(msgError)
        if (_campoError == null) {
            _campoError = mes;
        }
        return false;
    }
	if (!isInt(ano.value)) {
        appendErrorMessage(msgError)
        if (_campoError == null) {
            _campoError = ano;
        }
        return false;
	}
    if (!isDateDMY(dia.value + "/" + mes.options[mes.selectedIndex].value + "/" + ano.value) ||
        (funcion ? !eval("funcion(dia, mes, ano)") : false)) {
        appendErrorMessage(msgError)
        if (_campoError == null) {
            _campoError = dia;
        }
        return false;
    }
    return true;
}


function validarFechaOpcional(dia, mes, ano, msgError, funcion) {
	if (trim(dia.value).length > 0 ||
			mes.selectedIndex > 0 || trim(ano.value).length > 0) {
		return validarFecha(dia, mes, ano, msgError, funcion)
	}
}


function validarEntero(campo, msgError, limiteInferior, limiteSuperior,
		funcion) {
	if (!limiteInferior && limiteInferior != 0) {
		limiteInferior = Number.NEGATIVE_INFINITY
		limiteSuperior = Number.MAX_VALUE
	}
	if (!isIntRange(campo.value, limiteInferior, limiteSuperior) ||
        (funcion ? !eval("funcion(campo)") : false)) {
        appendErrorMessage(msgError)
        if (_campoError == null) {
            _campoError = campo;
        }
        return false;
	}
	return true;
}

function validarEnteroOpcional(campo, msgError, limiteInferior, limiteSuperior, funcion) {
	if (trim(campo.value).length > 0) {
		return validarEntero(campo, msgError, limiteInferior, limiteSuperior, funcion)
	}
}


function validarFloat(campo, msgError, limiteInferior, limiteSuperior, funcion) {
	if (!limiteInferior && limiteInferior != 0) {
		limiteInferior = Number.NEGATIVE_INFINITY
		limiteSuperior = Number.MAX_VALUE
	}
	if (!isFloatRange(campo.value, limiteInferior, limiteSuperior) ||
        (funcion ? !eval("funcion(campo)") : false)) {
        appendErrorMessage(msgError)
        if (_campoError == null) {
            _campoError = campo;
        }
        return false;
	}
	return true;
}

function validarFloatOpcional(campo, msgError, limiteInferior, limiteSuperior, funcion) {
	if (trim(campo.value).length > 0) {
		return validarFloat(campo, msgError, limiteInferior, limiteSuperior, funcion)
	}
}

function validarEmail(campo, msgError) {
	if (!isEmail(trim(campo.value))) {
        appendErrorMessage(msgError)
        if (_campoError == null) {
            _campoError = campo;
        }
        return false;
	}
	return true;
}


function validarEmailOpcional(campo, msgError) {
	if (trim(campo.value).length > 0) {
		return validarEmail(campo, msgError);
	}
}

 function controlarLongitudTextArea(teclaPresionada, campo, maximaLongitud) {
     var longitud = campo.value.length;

     var valTecla = teclaPresionada.which ? parseInt(teclaPresionada.which, 10)
             : (teclaPresionada.keyCode ? parseInt(teclaPresionada.keyCode, 10)
 : null);

     if (valTecla != null) {
         if ((valTecla != 8) && (valTecla != 46)) {
             if (longitud > maximaLongitud-1) {
                 return false;
             }
         }
     }
     return true;
 }



var _mensajeAdvertencia = "Por favor verifique la siguiente información: \n\n";

function validarForma(forma) {
	_errores = ""
	_campoError = null;

	eval("hacerValidaciones_" + forma.name +"(forma)");
	if (_errores != "") {
		alert(_mensajeAdvertencia + _errores);
		if (_campoError != null) {
			_campoError.focus();
		}
		return false;
	}
	return true;
}


/** 23 mayo 2007 */



var _valorGuardadoCamposForma = null;

function guardarValor(elCampo) {
	_valorGuardadoCamposForma = elCampo.value;
}

function restaurarValor(elCampo) {
	elCampo.value = _valorGuardadoCamposForma;
}


function noVacio(cadena) {
	if (!cadena && (cadena != 0)) {
		return "&nbsp;";
	}
	if ((cadena + " ") == " ") {
		return "&nbsp;";
	}

	var esBlanca = true;
	for (var i=0; i<cadena.length; i++) {
		if (cadena.charAt(i) != " ") {
			esBlanca = false;
			break;
		}
	}
	if (esBlanca) {
		return "&nbsp;";
	}
	return cadena;
}

// ago 14 2003  (dmontoya)
// actualización de separarMiles (tomada de última versión de rlopez)
function separarMiles(numero, numeroDecimales) {
    if ((numero + " ") == " ") {
        return "";
    }
    var negativo = (numero<0);
    if (negativo) {
        numero = -numero;
    }
    var entero = Math.floor(numero) + "";

    var decimal = calcularBaseDecimal(numero - entero);
    var decimalFormateado = "";
    var valorASumar = 0;
    if (numeroDecimales) {
        var baseDecimal = Math.round(rpad(decimal.substring(decimal.indexOf('.') + 1), "0", numeroDecimales*1 + 1)/10) + "";
        if (baseDecimal.length > numeroDecimales) {
            baseDecimal = baseDecimal.substring(1);
            valorASumar = 1;
        }
        decimalFormateado = "." + lpad(baseDecimal, "0", numeroDecimales);
    }
    entero = (entero*1 + valorASumar*1) + "";

    var enteroFormateado = "";
    var longitudPrimerGrupo = entero.length % 3;
    if ((longitudPrimerGrupo == 0) && (entero.length > 0)) {
        longitudPrimerGrupo = 3;
    }
    var enteroFormateado = entero.substring(0, longitudPrimerGrupo);

    for (var i=longitudPrimerGrupo; i<entero.length; i += 3) {
        enteroFormateado += "," + entero.substring(i, i + 3);
    }

    return (negativo ? "-":"") + enteroFormateado + decimalFormateado;
}

function calcularBaseDecimal(numero) {
    var strNumero = numero + "";
    var idxPunto = strNumero.indexOf(".");
    var idxNotCient = strNumero.indexOf("e-")
    if (idxNotCient != -1) {
        var cantidadCeros = strNumero.substring(idxNotCient + 2) - 1;
        strNumero = "0." + rpad("", "0", cantidadCeros) + strNumero.substring(0, idxPunto)
                + strNumero.substring(idxPunto +1, idxNotCient);
    }
    return strNumero;
}


function lpad(que, conQue, aCuanto) {
    var aRetornar = que;
    while (aRetornar.length < aCuanto) {
        aRetornar = ("" + conQue) + ("" + aRetornar);
    }
    var desde = aRetornar.length - aCuanto;
    return (desde > 0) ? aRetornar.substring(desde) : aRetornar;
}


function rpad(que, conQue, aCuanto) {
    var aRetornar = que;
    while (aRetornar.length < aCuanto) {
        aRetornar += "" + conQue;
    }
    return aRetornar.substring(0, aCuanto);
}
// fin ago 14 2003

  function lpad(que, conQue, aCuanto) {
      var aRetornar = que;
      while (aRetornar.length < aCuanto) {
          aRetornar = ("" + conQue) + ("" + aRetornar);
      }
      var desde = aRetornar.length - aCuanto;
      return (desde > 0) ? aRetornar.substring(desde) : aRetornar;
  }


  function rpad(que, conQue, aCuanto) {
      var aRetornar = que;
      while (aRetornar.length < aCuanto) {
          aRetornar += "" + conQue;
      }
      return aRetornar.substring(0, aCuanto);
  }

function validarComparacionFechasIguales(fecha1,fecha2,campo1, msgError) {
	
	var FP
	var FP1
	var date
	var date2
	date = trim(fecha1.value)
	FP = date.split("/")
	if (FP.length != 3) {
		return false
	}

	fechaInic=FP[0]+"/"+FP[1]+"/"+FP[2]

	date1 = trim(fecha2.value)
			FP1 = date1.split("/")
			if (FP1.length != 3) {
				return false
	}
	fechaFin=FP1[0]+"/"+FP1[1]+"/"+FP1[2]
	

	if (compareDatesDMY(fechaInic, fechaFin) > 0) {

		appendErrorMessage(msgError)		 
        if (_campoError == null) {
            _campoError = campo1;
        }
        return false;
	}

	return true;
}



