// ----------------------------------------------------------------------
// Rutinas para verificacion de formularios, basado en FormChek.js
// ---------------------------------------------------------------------- 

var defaultEmptyOK = false
var digits = "0123456789";
var lowercaseLetters = "abcdefghijklmnopqrstuvwxyz"
var uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var whitespace = " \t\n\r";
var phoneChars = "()-+ ";
var mMessage = "Error: no puede dejar este espacio vacio"
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 nmero de telfono";
var pEmail = "ingrese una direccin de correo electrnico vlida";
var pName = "ingrese un texto que contenga solo letras, numeros o espacios";

function makeArray(n) {
   for (var i = 1; i <= n; i++) {
      this[i] = 0
   } 
   return this
}

function isEmpty(s)
{   return ((s == null) || (s.length == 0)) }

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;
}

function isNotWhitespace (s)
{
    if (isWhitespace(s)) return false;
    return true;
}

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;
}

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;
}

function stripWhitespace (s)
{   return stripCharsInBag (s, whitespace) }

function charInString (c, s)
{   for (i = 0; i < s.length; i++)
    {   if (s.charAt(i) == c) return true; }
    return false
}

function stripInitialWhitespace (s)
{   var i = 0;
    while ((i < s.length) && charInString (s.charAt(i), whitespace))
       i++;
    return s.substring (i, s.length);
}

function isLetter (c)
{
    return( ( uppercaseLetters.indexOf( c ) != -1 ) ||
            ( lowercaseLetters.indexOf( c ) != -1 ) )
}

function isDigit (c)
{   return ((c >= "0") && (c <= "9")) }

function isLetterOrDigit (c)
{   return (isLetter(c) || isDigit(c)) }

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;
}

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;
}

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;
}

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;
}

function isName (s)
{
    if (isEmpty(s)) 
       if (isName.arguments.length == 1) return defaultEmptyOK;
       else return (isAlphanumeric.arguments[1] == true);
    return( isAlphanumeric( stripCharsInBag( s, whitespace ) ) );
}

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))
}

function isEmail (s)
{   if (isEmpty(s)) 
       if (isEmail.arguments.length == 1) return defaultEmptyOK;
       else return (isEmail.arguments[1] == true);
   
    // is s whitespace?
    if (isWhitespace(s)) return false;
    
    // there must be >= 1 character before @, so we
    // start looking at character position 1 
    // (i.e. second character)
    var i = 1;
    var sLength = s.length;

    // look for @
    while ((i < sLength) && (s.charAt(i) != "@"))
    { i++
    }

    if ((i >= sLength) || (s.charAt(i) != "@")) return false;
    else i += 2;

    // look for .
    while ((i < sLength) && (s.charAt(i) != "."))
    { i++
    }

    // there must be at least one character after the .
    if ((i >= sLength - 1) || (s.charAt(i) != ".")) return false;
    else return true;
}
function isNice(s)
{
        var i = 0;
        var sLength = s.length;
        var b = 1;
        while(i<sLength) {
                if( (s.charAt(i) == "\"") || (s.charAt(i) == "'" ) ) b = 0;
                i++;
        }
        return b;
}

function isNice2(s)
{
        var i = 0;
        var sLength = s.length;
        var b = false;
		if ( s.length != 0 )
		{
	        while(i<sLength) {
    	            if( (s.charAt(i) == '"') || (s.charAt(i) == "'" ) ) 
					b = true;
          	i++;
       		 }
		}
        return b;
}

function statBar (s)
{   window.status = s }

function warnEmpty (theField,msg)
{   theField.focus()
    //alert(mMessage)
    //alert(msg)
    statBar(mMessage)
    return false
}

function warnEmpty2 (theField,msg)
{   
    //alert(mMessage)
    //alert(msg)
    statBar(mMessage)
    return false
}

function warnInvalid (theField, s)
{   
    theField.focus();
    //theField.select() // Para que funcione en Explorer hay que comentarlo
    //alert(s);
    statBar(pPrompt + s);
    return false;
    //theField.focus()
}

function checkField (theField, theFunction, emptyOK, s)
{   
alert(theField.value)
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 == isPhoneNumber ) msg = pPhoneNumber;
if( theFunction == isName ) msg = pName;
}
if ((emptyOK == true) && (isEmpty(theField.value))) return true;
if ((emptyOK == false) && (isEmpty(theField.value))) 
	return warnEmpty(theField,msg);

if ( !isNice(theField.value)) 
	{
    
    return warnInvalid(theField, "No puede utilizar simbolos extranos ni comillas aqui");
    theField.focus();
    }

if (theFunction(theField.value) == true) 
	return true;
else
    {
	return warnInvalid(theField,msg);
    theField.focus();
    }
}

function warnInvalid2 (theField, s)
{   
    //alert(s)
    statBar(pPrompt + s)
    return false
}

function checkField2 (theField, theFunction, emptyOK, s)
{   
var msg;
if (checkField2.arguments.length < 3) emptyOK = defaultEmptyOK;
if (checkField2.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 == isPhoneNumber ) msg = pPhoneNumber;
if( theFunction == isName ) msg = pName;
}
if ((emptyOK == true) && (isEmpty(theField.value))) return true;
if ((emptyOK == false) && (isEmpty(theField.value))) 
	return warnEmpty2(theField,msg);

if ( !isNice(theField.value)) 
	return warnInvalid2(theField, "No puede utilizar simbolos extranos ni comillas aqui");

if (theFunction(theField.value) == true) 
	return true;
else
	return warnInvalid2(theField,msg);
}

function checkSelect (theField,s)
{
	if( theField.selectedIndex <= 0 )
	{
		return warnInvalid(theField, s);
	}
	return true;	
}


function chequeacampo (theField, theFunction, emptyOK, s)
{   
var msg;
if (chequeacampo.arguments.length < 3) emptyOK = defaultEmptyOK;
if (chequeacampo.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 == isPhoneNumber ) msg = pPhoneNumber;
if( theFunction == isName ) msg = pName;
}
if ((emptyOK == true) && (isEmpty(theField.value))) return true;
if ((emptyOK == false) && (isEmpty(theField.value))) 
	return warnEmpty(theField,msg);


if (theFunction(theField.value) == true) 
	return true;
else
	return warnInvalid(theField,msg);
}

function validarRut(s, e)
{
    if ( check_rut( e.Value.substring(0, e.Value.length - 1), e.Value.substring(e.Value.length - 1, e.Value.length ) ) )
    {
        e.IsValid = true;
    }
    else
    {
        e.IsValid = false;
    }
}

function validarFecha(s, e)
{
    var arrFecha

	arrFecha = e.Value.split("/");

	if (isDate(arrFecha[2], arrFecha[1], arrFecha[0]))
	{
        e.IsValid = true;
    }
    else
    {
        e.IsValid = false;
    }
}

function ValidarGlosas(s, e)
{
	if ( isNice( e.Value ))
    {
        e.IsValid = true;
    }
    else
    {
        e.IsValid = false;
    }
}


function ValidarCorreo (s, e)
{
 	if ( isEmail( e.Value ))
    {
        e.IsValid = true;
    }
    else
    {
        e.IsValid = false;
    }
}


function esNumero (s, e)
{
 	if ( isNumber( e.Value ))
    {
        e.IsValid = true;
    }
    else
    {
        e.IsValid = false;
    }
}

function NoVacioSelect (s, e)
{
	if( e.Value == '"' )
    {
        e.IsValid = false;
    }
    else
    {
        e.IsValid = true;
    }
}

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
}

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 isDate (year, month, day)
{   
    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;

    var intYear = parseInt(year, 10);
    var intMonth = parseInt(month, 10);
    var intDay = parseInt(day, 10);
	
	if (isNaN(intYear)) return false; 
    if (isNaN(intMonth)) return false;    
    if (isNaN(intDay)) return false;  
    if (!(year.length == 4)) return false;  
	  
    if ((intDay < 1) || (intDay > 31)) return false;
    if ((intMonth < 1) || (intMonth > 12)) return false;
		
    // catch invalid days, except for February
    if (intDay > daysInMonth[intMonth]) return false; 

    if ((intMonth == 2) && (intDay > daysInFebruary(intYear))) return false;

    return true;
}

function check_rut(rut,dv){
	dig_ver = dv;
	
	if ( isNaN(rut) ){
		//alert("Sólo deben ingresarse números en el RUT");
		return(false)
	}

	if ( rut.length < 7 || dig_ver == ""){
		//alert("El RUT debe contener 7 u 8 dígitos y 1 dígito verificador");
		return(false)
	} 

	if ( rut.length < 8 )
		numero_rut = "0" + rut
	else
		numero_rut = rut;


        v8 = numero_rut.substring(7,8) * 2;
        v7 = numero_rut.substring(6,7) * 3;
        v6 = numero_rut.substring(5,6) * 4;
        v5 = numero_rut.substring(4,5) * 5;
        v4 = numero_rut.substring(3,4) * 6;
        v3 = numero_rut.substring(2,3) * 7;
        v2 = numero_rut.substring(1,2) * 2;
        v1 = numero_rut.substring(0,1) * 3;

	suma_rut = v1 + v2 + v3 + v4 + v5 + v6 + v7 + v8;
	resto_rut = suma_rut % 11;

	digito_verificador = 11 - resto_rut;

	if ( digito_verificador == 10 )
		digito_verificador = "K";
	if ( digito_verificador == 11 )
		digito_verificador = 0;

        if ( digito_verificador == "K" ){
                if ( digito_verificador != dig_ver.toUpperCase() ){
                        //alert("El número de RUT esta incorrecto");
                        return (false)
                }
                else
                        return (true);
        } else {
                if ( digito_verificador != dig_ver ){
                        //alert("El número de RUT esta incorrecto");
                        return (false)
                }
                else
                        return (true);
        }

}

function verify_ccard(type,inNumber)
{

	if(type == "0")
	{	
		message="No ha seleccionado el tipo de tarjeta de crédito";
		//alert(message);
		return (0);
	}

        total = 1*0;
        tmp = 1*0;

        number = "";
        

        // make sure there are only numbers in the string...
        for(i = 0; i < inNumber.length; i++)
        {
		if(inNumber.charAt(i) >= "0" && inNumber.charAt(i) <= "9")
                {
                        number = number + inNumber.charAt(i);
                }
        }

        if(number.length < 13) return 10; // too short for anything

        first = "" + number.charAt(0);
        second = "" + number.charAt(1);
        third = "" + number.charAt(2);
        firstTwo = first + second;
        firstFour = firstTwo + third + number.charAt(3);

        if(type == "Master" ) // "MASTERCARD"
        {
                if(first != "5" || second < "1" || second > "5")
                        return 11;// invalid Mastercard prefix
                if(number.length != 16)
                        return 21;
        }
        else if(type == "Visa" ) // "VISA"
        {
                if(first != "4")
                        return 12;// invalid Visa prefix
                if(number.length != 13 && number.length != 16)
                        return 22;
        }
        else if(type == "4") // "AMERICAN EXPRESS"
        {
                if(first != "3" || (second != "4" && second != "7"))
                        return 13;// invalid American Express Prefix
                if(number.length != 15) 
                        return 23;
        }
        else if(type == "DISC")
        {
                        if(firstFour != "6011")
                                return 14;// invalid prefix.
                        if(number.length != 16)
                                return 24;
        }
        else if(type == "Dinners") // "DINNERS"
        {
                if(firstTwo != "36"
                        && firstTwo != "38"
                        && (firstTwo != "30" ||
                                (third < "0" || third > "5")))
                {
                        return 15;
                }
                if(number.length != 14)
                        return 25;
        }
        else if(type == "enRoute")
        {
                if(firstFour != "2014"
                        && firstFour != "2149")
                        return 16;// invalid enRoute card
                if(number.length != 15)
                        return 26;
		return 0; // no check sum calculation needed
        }
        else if(type == "JCB")
        {
                if(firstFour != "2131"
                        && firstFour != "1800"
                        && (first != "3") )
                        return 17;
                if(number.length != 16 && first =="3")
                        return 27;
                if(number.length != 15 && first != "3")
                        return 28;
        }
        // now check the credit card suffix and length vs. the type
         // do the check sum
        for(loc = number.length - 2; loc >= 0; loc -= 2)
        {
                total += 1 * number.charAt(loc +1);
                tmp = number.charAt(loc) * 2;
		if(tmp > 9) total += 1;
		total += tmp%10;
        }
	if(number.length % 2 > 0)
	total += 1 * number.charAt(0);

        return (total % 10);
}
