// ---------------------------------------------------------------------- //
//                                VARIABLES                               //
// ---------------------------------------------------------------------- //
// Esta variable indica si está bien dejar las casillas
// en blanco como regla general
var defaultEmptyOK = false
// listas de caracteres
var digits = "0123456789";
var lowercaseLetters = "abcdefghijklmnopqrstuvwxyzáéíóúñü"
var uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZÁÉÍÓÚÑ_"
var whitespace = " \t\n\r";

// caracteres admitidos en campos de telefono
var phoneChars = "()-+ ";

// ---------------------------------------------------------------------- //
//                     TEXTOS PARA LOS MENSAJES                           //
// ---------------------------------------------------------------------- //

// m abrevia "missing" (faltante)
var mMessage = "Error: no puede dejar este espacio vacio, es obligatorio "
// p abrevia "prompt"
var pPrompt = "Error: ";
var pAlphanumeric = "Ingrese un texto que contenga solo letras y/o numeros";
var pAlphabetic   = "Ingrese un texto que contenga solo letras";
var pInteger = "Ingrese un numero entero";
var pNumber = "Ingrese un numero";
var pPhoneNumber = "Ingrese un número de teléfono";
var pEmail = "Ingrese una dirección de correo electrónico válida\n Ej: agv@i.cl";
var pName = "Ingrese un texto que contenga solo letras, numeros";

var antes = "Error: Debe ingresar un valor válido en el campo ["
var despues = "], Por favor";


// ---------------------------------------------------------------------- //
//                FUNCIONES PARA MANEJO DE ARREGLOS                       //
// ---------------------------------------------------------------------- //
function makeArray(n) {
//*** BUG: If I put this line in, I get two error messages:
//(1) Window.length can't be set by assignment
//(2) daysInMonth has no property indexed by 4
//If I leave it out, the code works fine.
//   this.length = n;
   for (var i = 1; i <= n; i++) {
      this[i] = 0
   } 
   return this
}
// ---------------------------------------------------------------------- //
//                  CODIGO PARA FUNCIONES BASICAS                         //
// ---------------------------------------------------------------------- //

// s es vacio
function isEmpty(s)
{   return ((s == null) || (s.length == 0))
}
// s es vacio o solo caracteres de espacio
function isWhitespace (s)
{   var i;
    if (isEmpty(s)) return true;
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        // si el caracter en que estoy no aparece en whitespace,
        // entonces retornar falso
        if (whitespace.indexOf(c) == -1) return false;
    }
    return true;
}

// Quita todos los caracteres que que estan en "bag" del string "s" s.
function stripCharsInBag (s, bag)
{   var i;
    var returnString = "";

    // Buscar por el string, si el caracter no esta en "bag", 
    // agregarlo a returnString
    
    for (i = 0; i < s.length; i++)
    {   var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }

    return returnString;
}

// Lo contrario, quitar todos los caracteres que no estan en "bag" de "s"
function stripCharsNotInBag (s, bag)
{   var i;
    var returnString = "";
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if (bag.indexOf(c) != -1) returnString += c;
    }

    return returnString;
}

// Quitar todos los espacios en blanco de un string
function stripWhitespace (s)
{   return stripCharsInBag (s, whitespace)
}

// La rutina siguiente es para cubrir un bug en Netscape
// 2.0.2 - seria mejor usar indexOf, pero si se hace
// asi stripInitialWhitespace() no funcionaria

function charInString (c, s)
{   for (i = 0; i < s.length; i++)
    {   if (s.charAt(i) == c) return true;
    }
    return false
}

// Quita todos los espacios que antecedan al string
function stripInitialWhitespace (s)
{   var i = 0;
    while ((i < s.length) && charInString (s.charAt(i), whitespace))
       i++;
    return s.substring (i, s.length);
}

// c es una letra del alfabeto espanol
function isLetter (c)
{
    return( ( uppercaseLetters.indexOf( c ) != -1 ) ||
            ( lowercaseLetters.indexOf( c ) != -1 ) )
}

// c es un digito
function isDigit (c)
{   return ((c >= "0") && (c <= "9"))
}

// c es letra o digito
function isLetterOrDigit (c)
{   return (isLetter(c) || isDigit(c))
}

// ---------------------------------------------------------------------- //
//                          NUMEROS                                       //
// ---------------------------------------------------------------------- //

// s es un numero entero (con o sin signo)
function isInteger (s)
{   var i;
    if (isEmpty(s)) 
       if (isInteger.arguments.length == 1) return defaultEmptyOK;
       else return (isInteger.arguments[1] == true);
    
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if( i != 0 ) {
            if (!isDigit(c)) return false;
        } else { 
            if (!isDigit(c) && (c != "-") || (c == "+")) return false;
        }
    }
    return true;
}

// s es un numero (entero o flotante, con o sin signo)
function isNumber (s)
{   var i;
    var dotAppeared;
    dotAppeared = false;
    if (isEmpty(s)) 
       if (isNumber.arguments.length == 1) return defaultEmptyOK;
       else return (isNumber.arguments[1] == true);
    
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if( i != 0 ) {
            if ( c == "." ) {
                if( !dotAppeared )
                    dotAppeared = true;
                else
                    return false;
            } else     
                if (!isDigit(c)) return false;
        } else { 
            if ( c == "." ) {
                if( !dotAppeared )
                    dotAppeared = true;
                else
                    return false;
            } else     
                if (!isDigit(c) && (c != "-") || (c == "+")) return false;
        }
    }
    return true;
}

// ---------------------------------------------------------------------- //
//                        STRINGS SIMPLES                                 //
// ---------------------------------------------------------------------- //
// s tiene solo letras
function isAlphabetic (s)
{   var i;

    if (isEmpty(s)) 
       if (isAlphabetic.arguments.length == 1) return defaultEmptyOK;
       else return (isAlphabetic.arguments[1] == true);
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is letter.
        var c = s.charAt(i);

        if (!isLetter(c))
        return false;
    }
    return true;
}

// s tiene solo letras y numeros
function isAlphanumeric (s)
{   var i;

    if (isEmpty(s)) 
       if (isAlphanumeric.arguments.length == 1) return defaultEmptyOK;
       else return (isAlphanumeric.arguments[1] == true);

    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if (! (isLetter(c) || isDigit(c) ) )
        return false;
    }

    return true;
}

// s tiene solo letras, numeros o espacios en blanco
function isName (s)
{
    if (isEmpty(s)) 
       if (isName.arguments.length == 1) return defaultEmptyOK;
       else return (isAlphanumeric.arguments[1] == true);
    
    return( isAlphanumeric( stripCharsInBag( s, whitespace ) ) );
}

// ---------------------------------------------------------------------- //
//                           FONO o EMAIL                                 //
// ---------------------------------------------------------------------- //

// s es numero de telefono valido
function isPhoneNumber (s)
{   var modString;
    if (isEmpty(s)) 
       if (isPhoneNumber.arguments.length == 1) return defaultEmptyOK;
       else return (isPhoneNumber.arguments[1] == true);
    modString = stripCharsInBag( s, phoneChars );
    return (isInteger(modString))
}

// s es una direccion de correo valida
function isEmail (s)
{
    if (isEmpty(s)) 
       if (isEmail.arguments.length == 1) return defaultEmptyOK;
       else return (isEmail.arguments[1] == true);
    if (isWhitespace(s)) return false;
    var i = 1;
    var sLength = s.length;
    while ((i < sLength) && (s.charAt(i) != "@"))
    { i++
    }

    if ((i >= sLength) || (s.charAt(i) != "@")) return false;
    else i += 2;

    while ((i < sLength) && (s.charAt(i) != "."))
    { i++
    }

    if ((i >= sLength - 1) || (s.charAt(i) != ".")) return false;
    else return true;
}

// ---------------------------------------------------------------------- //
//                  FUNCIONES PARA RECLAMARLE AL USUARIO                  //
// ---------------------------------------------------------------------- //

// pone el string s en la barra de estado
function statBar (s)
{   window.status = s
}

// notificar que el campo theField esta vacio
function warnEmpty (theField,s)
{   theField.focus()		
    //original alert(mMessage+s)
    alert(antes + s + despues)
    //original statBar(mMessage)
    statBar(antes + s + despues)
    return false
}

// notificar que el campo theField es invalido
function warnInvalid (theField, s)
{   theField.focus()
    theField.select()
    //original alert(s)
    alert(antes + s + despues)
    statBar(pPrompt + s)
    return false
}
//
function isBlanco (s)
{   var i;
    if (isEmpty(s)) return false;
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        // si el caracter en que estoy no aparece en whitespace,
        // entonces retornar falso
        if (whitespace.indexOf(c) == -1) return true;
    }
    return false;
}

// el corazon de todo: checkField
function checkField (theField, theFunction, emptyOK, s)
{   
    var msg;
    if (checkField.arguments.length < 3) emptyOK = defaultEmptyOK;
    if (checkField.arguments.length == 4) {
        msg = s;
    } else {
        //if( theFunction == isAlphabetic ) msg = pAlphabetic;
        if( theFunction == isAlphanumeric ) msg = pAlphanumeric;
        //if( theFunction == isInteger ) msg = pInteger;
        //if( theFunction == isNumber ) msg = pNumber;
        if( theFunction == isEmail ) msg = pEmail;
        if( theFunction == isName ) msg = pName;
        //if( theFunction == isPhoneNumber ) msg = pPhoneNumber;        
    }    
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;

    if ((emptyOK == false) && (isEmpty(theField.value))) 
        return warnEmpty(theField, s); //aqui

    if (theFunction(theField.value) == true) 
        return true;
    else
        return warnInvalid(theField,msg);
}
function vDetalle(){
	var objHT = document.getElementById('hT');
	if(parseInt(objHT.value)<14000 || objHT.value==''){
		alert('Sólo se realizan pedidos iguales o superiores a $14.000.');
		return false;
	}
	return true;
}

function VerifyOneCP () {
	if(!(checkField( document.fFormulario.tNombre, isBlanco, false, 'Nombre' )&&
			checkField( document.fFormulario.tEmail, isEmail, false, 'E-mail' ) &&                
      checkField( document.fFormulario.tEmpresa, isBlanco, true, 'Empresa' ) &&        
      checkField( document.fFormulario.tRut, checkRutField, false, 'RUT' ) &&
      checkField( document.fFormulario.tTelefono, isBlanco, false, 'Teléfonos donde contactarlo' ) &&
      checkField( document.fFormulario.tAsunto, isBlanco, false, 'Asunto o tema del mensaje' ) &&
      checkField( document.fFormulario.tMensaje, isBlanco, false, 'Mensaje' )
	   )){
			return false;
		 }
	return true;
}

function VerifyTwoCP () {
	if(!(checkField( document.fFormulario.tNombre, isBlanco, false, 'Nombre' )&&
			checkField( document.fFormulario.tEmail, isEmail, true, 'E-mail' ) &&                
      checkField( document.fFormulario.tTelefono, isBlanco, false, 'Teléfonos donde contactarlo' ) &&
      checkField( document.fFormulario.tMensaje, isBlanco, false, 'Mensaje' )
	   )){
			return false;
		 }
	return true;
}

function VerifySolCP () {
	if(!(checkField( document.fFormulario.tNombre, isBlanco, false, 'Nombre' )&&
		checkField( document.fFormulario.tEmail, isEmail, false, 'E-mail' ) &&                
      checkField( document.fFormulario.tEmpresa, isBlanco, true, 'Empresa' ) &&        
      checkField( document.fFormulario.vchRut, checkRutField, false, 'RUT' ) &&
      checkField( document.fFormulario.tTelefono, isBlanco, false, 'Teléfonos donde contactarlo' ) &&
      checkField( document.fFormulario.tFax, isBlanco, false, 'Fax' ) &&
      checkField( document.fFormulario.tMensaje, isBlanco, false, 'Comentarios' )
	   )){
			return false;
		 }
	return true;
}

function VerificaClaves(objClave1, objClave2)
{
  if (objClave1.value != objClave2.value)
  {
    alert("Las Claves Son Distintas, favor verifique.");
    objClave1.focus();
    return false;
  }
  return true;
}

function validaFechaNac(objDia, objMes, objAno)
{  
	var dia = objDia.value;
	var mes = objMes.value;
	var ano = objAno.value;
	if(!isDate(ano, mes, dia)){
		alert(antes + 'Fecha de Nacimiento' + despues);
		objDia.focus();
		return false;
	}
	return true;
}

function validaCombos(obj, str){
	if(obj.selectedIndex == -1){
		alert('Error, es necesario que seleccione una opción en el campo [' + str + ']');
		obj.focus();
		return false;
	}
	return true;
}

function fSacarComas(o, msg){
	if(o.value.indexOf(',')>-1){
		alert(antes + msg + despues);
		o.focus();
		return false;
	}
	if(o.value.indexOf('~')>-1 || o.value.indexOf('|')>-1){
		alert(antes + msg + despues);
		o.focus();
		return false;
	}
	return true;
}

function VerificaLargoClaves(objClave1)
{
  if (objClave1.value.length<6)
  {
    alert("Error, la clave debe tener como Mínimo 6 caracteres, favor verifique.");
    objClave1.focus();
		objClave1.select();
    return false;
  }
  return true;
}

function VerifyUsuario() {
if(document.fFormulario.Edad.value!=''){
 if(isNaN(parseInt(document.fFormulario.Edad.value))){alert('Debe ingresar un valor numérico en la edad');return false;document.fFormulario.Edad.focus();}
   document.fFormulario.ano.value=parseInt(parseInt(now.getFullYear())-parseInt(document.fFormulario.Edad.value));
}
//if(document.fFormulario.CAM_36[document.fFormulario.CAM_36.selectedIndex].value!='578' && document.fFormulario.vchRut.value=''){document.fFormulario.vchRut.focus();}
if( 
				checkField(document.fFormulario.vchNombres, isName, false, 'Nombres' ) &&
				checkField(document.fFormulario.vchApellidos, isBlanco, true, 'Apellidos' ) &&
				fSacarComas(document.fFormulario.vchApellidos, 'Apellidos') &&
				//checkField(document.fFormulario.vchRut, checkRutField, false, 'Rut' ) &&
				validaCombos(document.fFormulario.CAM_10, 'Nacionalidad') &&
				//validaCombos(document.fFormulario.dia, 'Día de Nacimiento') &&
				//validaCombos(document.fFormulario.mes, 'Mes de Nacimiento') &&
				//validaCombos(document.fFormulario.ano, 'Año de Nacimiento') &&
				validaCombos(document.fFormulario.CAM_1, 'Sexo') &&
				checkField( document.fFormulario.Edad, isBlanco, false, 'Edad' ) &&
				fSacarComas ( document.fFormulario.vchTelefono, 'Teléfonos') &&
				fSacarComas(document.fFormulario.vchEmailPrin, 'E-mail personal') &&
				checkField(document.fFormulario.vchEmailPrin, isEmail, false, 'E-mail personal' ) &&
				//validaCombos(document.fFormulario.CAM_25, 'Región donde vive') &&
				//checkField( document.fFormulario.ID_vchUsuarioAux, isBlanco, false, 'E-mail de Registro' ) &&
				//fSacarComas ( document.fFormulario.ID_vchUsuarioAux, 'E-mail de Registro') &&
				checkField(document.fFormulario.vchClave, isBlanco, false, 'Clave' ) &&
				fSacarComas(document.fFormulario.vchClave, 'Clave') &&
				checkField(document.fFormulario.repvchClave, isBlanco, false, 'Confirmación de la clave' ) &&
				fSacarComas(document.fFormulario.repvchClave, 'Confirmación de la clave') &&
				checkField(document.fFormulario.vchPreguntaOlvido, isBlanco, false, 'Pregunta para recordar tu clave' ) &&
				fSacarComas(document.fFormulario.vchPreguntaOlvido, 'Pregunta para recordar tu clave') &&
				checkField(document.fFormulario.vchRespuestaOlvido, isBlanco, false, 'Respuesta a la pregunta' ) &&
				fSacarComas(document.fFormulario.vchRespuestaOlvido, 'Respuesta a la pregunta') &&
				//validaFechaNac(document.fFormulario.dia, document.fFormulario.mes, document.fFormulario.ano) &&
				VerificaClaves(document.fFormulario.vchClave, document.fFormulario.repvchClave))
    {
			//alert('gracias por registrarse');
			return true;
		} 
		else
		{
			return false;
		}
}



function checkUsuario (f) {
    if( checkField(f.ID_vchUsuarioAux, isBlanco, false, 'Usuario de Registro' )){
			return true;
		}
		return false;
}