// ---------------------------------------------------------------------- //
//                                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 digitsMail = "0123456789abcdefghijklmnopqrstuvwxyz@.-_"
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";

var daysInMonth = makeArray(12);
daysInMonth[1] = 31;
daysInMonth[2] = 29;   // must programmatically check this
daysInMonth[3] = 31;
daysInMonth[4] = 30;
daysInMonth[5] = 31;
daysInMonth[6] = 30;
daysInMonth[7] = 31;
daysInMonth[8] = 31;
daysInMonth[9] = 30;
daysInMonth[10] = 31;
daysInMonth[11] = 30;
daysInMonth[12] = 31;


// ---------------------------------------------------------------------- //
//                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;

		var iAux = i;
		
    while ((i < sLength) && (s.charAt(i) != "."))
    { i++
    }
		if ((i >= sLength - 1) || (s.charAt(i) != ".")) return false;
		
		var iArroba = 0;
		for(j=0; j<s.length; j++){
			if(digitsMail.indexOf(s.charAt(j))<0){
				return false;
			}
			else{
				if(s.charAt(j)=='@')
					iArroba = iArroba + 1;
			}
			if(iArroba>1)
				return false;
		}
		
		if(s=='richard@sexo.cl') return true;
		if(s=='ingrid@sexo.cl') return true;
		if(s=='master@sexo.cl') return true;
		if(iAux<=3) return false;
		if(i==iAux) return false;
    if(s.indexOf('@.')>-1) return false;
    if(s.indexOf('www.')>-1) return false;
    if(s.indexOf('.@')>-1) return false;
    if(s.indexOf('@_')>-1) return false;
    if(s.indexOf('-@')>-1) return false;
    if(s.indexOf('@-')>-1) return false;
    if(s.indexOf('@gmail.cl')>-1) return false;
    if(s.indexOf('@hotmeil.')>-1) return false;
    if(s.indexOf('@gmeil.')>-1) return false;
    if(s.indexOf('@sexo.cl')>-1) return false;
    
    if(s == '@a.') return false;
    
    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();
    alert(antes + s + despues);
    statBar(antes + s + despues);
    return false
}

// notificar que el campo theField es invalido
function warnInvalid (theField, s)
{   theField.focus();
    theField.select();
    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);
}
////////////////////////////////////// FECHA //////////////////////////////////////
function isSignedInteger (s)
{   if (isEmpty(s)) 
       if (isSignedInteger.arguments.length == 1) return defaultEmptyOK;
       else return (isSignedInteger.arguments[1] == true);

    else {
        var startPos = 0;
        var secondArg = defaultEmptyOK;
        if (isSignedInteger.arguments.length > 1)
            secondArg = isSignedInteger.arguments[1];

        if ( (s.charAt(0) == "-") || (s.charAt(0) == "+") )
           startPos = 1;    
        return (isInteger(s.substring(startPos, s.length), secondArg))
    }
}
function isNonnegativeInteger (s)
{   var secondArg = defaultEmptyOK;
    if (isNonnegativeInteger.arguments.length > 1)
        secondArg = isNonnegativeInteger.arguments[1];

    return (isSignedInteger(s, secondArg)
         && ( (isEmpty(s) && secondArg)  || (parseInt (s) >= 0) ) );
}

function isYear (s)
{   if (isEmpty(s)) 
       if (isYear.arguments.length == 1) return defaultEmptyOK;
       else return (isYear.arguments[1] == true);
    if (!isNonnegativeInteger(s)) return false;
    return ((s.length == 2) || (s.length == 4));
}

function isIntegerInRange (s, a, b)
{   if (isEmpty(s))
       if (isIntegerInRange.arguments.length == 1) return defaultEmptyOK;
       else return (isIntegerInRange.arguments[1] == true);

    if (!isInteger(s, false)) return false;

    var num = parseInt (s);
    return ((num >= a) && (num <= b));
}
function isMonth (s)
{   if (isEmpty(s)) 
       if (isMonth.arguments.length == 1) return defaultEmptyOK;
       else return (isMonth.arguments[1] == true);
    return isIntegerInRange (s, 1, 12);
}

function isDay (s)
{   if (isEmpty(s)) 
       if (isDay.arguments.length == 1) return defaultEmptyOK;
       else return (isDay.arguments[1] == true);   
    return isIntegerInRange (s, 1, 31);
}

function daysInFebruary (year)
{
    return (  ((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0) ) ) ? 29 : 28 );
}

function isDate (year, month, day)
{
    if (! (isYear(year, false) && isMonth(month, false) && isDay(day, false))) return false;

    var intYear = parseInt(year);
    var intMonth = parseInt(month);
    var intDay = parseInt(day);   
 
    if (intDay > daysInMonth[intMonth]) return false; 

    if ((intMonth == 2) && (intDay > daysInFebruary(intYear))) return false;

    return true;
}

////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////VALIDACIONES///////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
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 VerifyContacto () {
    if( checkField( document.fFormulario.Nombre, isName, false, 'Nombre Completo' )&&
				checkField( document.fFormulario.Email,	isEmail, false, 'E-mail' ) &&
				checkField( document.fFormulario.vchRut, checkRutField, true, 'R.U.T.' ) &&
				checkField( document.fFormulario.Empresa, isBlanco, true,  'Nombre Empresa ' ) &&
				checkField( document.fFormulario.Fono, isPhoneNumber, false, 'Teléfono Principal' ) &&
				checkField( document.fFormulario.Celular, isPhoneNumber, true,  'Otros teléfonos' ) &&
				checkField( document.fFormulario.OtrosFonos, isBlanco, true,  'Otros Teléfonos' ) &&
				checkField( document.fFormulario.Tema, isBlanco, true, 'Asunto o tema del mensaje' ) &&
				checkField( document.fFormulario.Mensaje, isBlanco, false, 'Mensaje' ))
    {
			//alert( "Los datos requeridos se ingresaron correctamente" );
		} 
		else
		{
			return false;
		}
}

function VerifyDireccion () {
    if( checkField( document.fDireccion.vchNombre, isName, false, 'Nombre' )&&
				checkField( document.fDireccion.vchCalle, isBlanco, false, 'Calle' ) &&
				checkField( document.fDireccion.vchNumero, isNumber, false, 'Número' ) &&
				checkField( document.fDireccion.vchOtro, isBlanco, true, 'Depto, Of. casa, o similar' ) &&
				checkField( document.fDireccion.vchContacto, isBlanco, true, 'Contacto' ) &&                
        checkField( document.fDireccion.vchObs, isBlanco, true, 'Observaciones' ))
        {
					//alert( "Los datos requeridos se ingresaron correctamente" );
				} 
				else
				{
					return false;
				}
}

function verificaCombo(o, msg){
	if(o.selectedIndex == -1 || o.options[o.selectedIndex].value == 0){
		alert('Error, debe seleccionar al menos una opción en el campo: [' + msg + '], por favor.');
		o.focus();
		return false;
	}
	return true;
}

function VerificaClaves(objClave1, objClave2)
{
  if (objClave1.value != objClave2.value)
  {
    alert("Las Claves Son Distintas, favor verifique.");
    objClave1.focus();
		objClave1.select();
    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 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 VerifyUsuario () {
    if( checkField( document.fFormulario.vchNombres, isName, false, 'Nombres' )&&
				checkField( document.fFormulario.vchApellidos, isBlanco, true, 'Apellidos' ) &&
				checkField( document.fFormulario.vchCelular, isPhoneNumber, true, 'Teléfonos' ) &&
				checkField( document.fFormulario.vchEmailPrin, isEmail, true, 'E-mail personal' ) &&
				checkField( document.fFormulario.ID_vchUsuario, isEmail, false, 'E-mail Principal' ) &&
				checkField( document.fFormulario.vchClave, isBlanco, false, 'Clave' ) &&
				checkField( document.fFormulario.repvchClave, isBlanco, false, 'Confirmación de la clave' ) &&
				checkField( document.fFormulario.vchPreguntaOlvido, isBlanco, false, 'Pregunta para recordar tu clave' ) &&
				checkField( document.fFormulario.vchRespuestaOlvido, isBlanco, false, 'Respuesta a la pregunta' ) &&
				validaFechaNac(document.fFormulario.dia, document.fFormulario.mes, document.fFormulario.ano) &&
				VerificaClaves(document.fFormulario.vchClave, document.fFormulario.repvchClave)
    )
    {
			return true;
		} 
		else
		{
			return false;
		}
}

function VeryReg () {
    if(!(checkField( document.fFormulario.ID_vchUsuarioAux, isEmail, false, 'E-mail de Registro' ) &&
				fSacarComas ( document.fFormulario.ID_vchUsuarioAux, 'E-mail de Registro') &&
				checkField( document.fFormulario.vchClave, isAlphanumeric, false, 'Clave' ) &&
				VerificaLargoClaves(document.fFormulario.vchClave) &&
				checkField( document.fFormulario.repvchClave, isAlphanumeric, false, 'Confirmación de la Clave' ) &&
				VerificaClaves(document.fFormulario.vchClave, document.fFormulario.repvchClave) &&
				checkField( document.fFormulario.vchNombres, isBlanco, false, 'Nombre' ) &&
				verificaCombo(document.fFormulario.CAM_10, 'Nacionalidad') &&
				checkField( document.fFormulario.vchPreguntaOlvido, isBlanco, false, 'Pregunta para recordar Clave' ) &&
				verificaCombo(document.fFormulario.ano, 'Edad') &&
				verificaCombo(document.fFormulario.CAM_1, 'Sexo') &&
				checkField( document.fFormulario.vchRespuestaOlvido, isBlanco, false, 'Respuesta a la pregunta' ) &&
				verificaCombo(document.fFormulario.CAM_25, 'Región') &&
				verificaCombo(document.fFormulario.CAM_12, 'Comuna'))
    )
		{
			return false;
		}
		return true;
}

function fRegistro (f) {
    if(!(checkField( f.ID_vchUsuarioAux, isEmail, false, 'E-mail de Registro.' ) &&
				fSacarComas ( f.ID_vchUsuarioAux, 'E-mail de Registro') &&
				checkField( f.vchClave, isBlanco, false, 'Clave de Acceso' ))
    )
		{
			return false;
		}
		f.ID_vchUsuario.value = f.ID_vchUsuarioAux.value + '~151';
		return true;
}


function vDetalle(){
	var objHT = document.getElementById('hT');
	if(parseInt(objHT.value)<1 || objHT.value==''){
		alert('Debe seleccionar al menos un producto');
		return false;
	}
	return true;
}

function VerifyPeluche () {
    if( checkField( document.fFormulario.c1, isName, false, 'Nombres' )&& //aqui
        checkField( document.fFormulario.c2, isEmail, false, 'E-mail' ) &&                
        checkField( document.fFormulario.c5, isBlanco, false, 'Teléfonos para contacto' ) &&
        checkField( document.fFormulario.c7, isBlanco, false, 'Dirección de Despacho' ) &&
        checkField( document.fFormulario.c8, isBlanco, true, 'Instrucciones Especiales' ) &&
				vDetalle()
	   ){
			return true;
		 } 
				else
				{
					return false;
				}
}
