/* Validate.js, version 1.0.2
*  (c) 2006 achraf bouyakhsass <mutation[at]mutationevent.com>
* 
*  This software is licensed under the CC-GNU GPL
*  http://creativecommons.org/licenses/GPL/2.0/
*
*  For more details
*  http://www.mutationevent.com/project/validate.js
*
*  Package to validate various data :
*  isEqual
*  hasValidChars
*  isSimpleIP
*  isAlphaLatin
*  isNotEmpty
*  isIntegerInRange
*  isNum
*  isEMailAddr
*  isZipCode
*  isDate
*  isMD5
*  isURL
*  isGuid
*  isISBN
*  isSSN
*  isDecimal
*  iscpf
*  iscnpj
*
*  Mascara
*  MASCARA_MOEDA
*  isplatform
*  addRules
*  Apply
/*--------------------------------------------------------------------------*/
var Class = {
    create: function() {
        return function() {
            this.initialize.apply(this, arguments);
        }
    }
}

function getValue(s){
    return document.getElementById(s).value
    }

var Validate = Class.create();
Validate.prototype = {
    /*--------------------------------------------------------------------------*/
    initialize:function(){
        this.error_array = []
        this.rules_array = [];
        this.e = true;
    },
    /*--------------------------------------------------------------------------*/
    isEqual:function(string1, string2){
        if(string1 == string2) return true;
        else return false;
    },
    /*--------------------------------------------------------------------------*/
    hasValidChars:function(s, characters, caseSensitive){
        function escapeSpecials(s){
            return s.replace(new RegExp("([\\\\-])", "g"), "\\$1");
        }
        return new RegExp("^[" + escapeSpecials(characters) + "]+$",(!caseSensitive ? "i" : "")).test(s);
    },
    /*--------------------------------------------------------------------------*/
    isSimpleIP:function(ip){
        ipRegExp = /^(([0-2]*[0-9]+[0-9]+)\.([0-2]*[0-9]+[0-9]+)\.([0-2]*[0-9]+[0-9]+)\.([0-2]*[0-9]+[0-9]+))$/
        return ipRegExp.test(ip);
    },
    /*--------------------------------------------------------------------------*/
    isAlphaLatin:function(string){
        alphaRegExp = /^[0-9a-z]+$/i
        return alphaRegExp.test(string);
    },
    /*--------------------------------------------------------------------------*/
    isLogin:function(string){
        alphaRegExp = /^[0-9a-z]+$/i
        var retorno= alphaRegExp.test(string);
        if(string.length<6){
            retorno=false;
        }
        return retorno;
    }
    ,
    /*--------------------------------------------------------------------------*/
    isChars:function(string){
        charRegExp = /^[a-z A-Z]+$/
        return charRegExp.test(string);
    },
    /*--------------------------------------------------------------------------*/
    isNotEmpty:function (string){
        return /\S/.test(string);
    },
    /*--------------------------------------------------------------------------*/
    isEmpty:function(s){
        return !/\S/.test(s);
    },
    /*--------------------------------------------------------------------------*/
    isPass:function(valor){
        if(valor.length<=5){
            return false;
        }else{
            return true;
        }
    },
    /*--------------------------------------------------------------------------*/
    iscnpj:function(cnpj){
        var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais;
        digitos_iguais = 1;
        cnpj=cnpj.replace('.','');
        cnpj=cnpj.replace('.','');
        cnpj=cnpj.replace('-','');
        cnpj=cnpj.replace('/','');
        if (cnpj.length < 14 || cnpj.length > 15){
            return false;
        }
        for (i = 0; i < cnpj.length - 1; i++)
            if (cnpj.charAt(i) != cnpj.charAt(i + 1))
            {
                digitos_iguais = 0;
                break;
            }
        if (!digitos_iguais)
        {
            tamanho = cnpj.length - 2;
            numeros = cnpj.substring(0,tamanho);
            digitos = cnpj.substring(tamanho);
            soma = 0;
            pos = tamanho - 7;
            for (i = tamanho; i >= 1; i--)
            {
                soma += numeros.charAt(tamanho - i) * pos--;
                if (pos < 2)
                    pos = 9;
            }
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
            if (resultado != digitos.charAt(0))
                return false;
            tamanho = tamanho + 1;
            numeros = cnpj.substring(0,tamanho);
            soma = 0;
            pos = tamanho - 7;
            for (i = tamanho; i >= 1; i--)
            {
                soma += numeros.charAt(tamanho - i) * pos--;
                if (pos < 2)
                    pos = 9;
            }
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
            if (resultado != digitos.charAt(1))
                return false;
            return true;
        }
        else
            return false;
    },
    /*--------------------------------------------------------------------------*/
    iscpf: function(cpf){
        var numeros, digitos, soma, i, resultado, digitos_iguais;
        digitos_iguais = 1;
        cpf=cpf.replace('.','');
        cpf=cpf.replace('.','');
        cpf=cpf.replace('-','');
        if (cpf.length < 11)
            return false;
        for (i = 0; i < cpf.length - 1; i++)
            if (cpf.charAt(i) != cpf.charAt(i + 1))
            {
                digitos_iguais = 0;
                break;
            }
        if (!digitos_iguais)
        {

            numeros = cpf.substring(0,9);
            digitos = cpf.substring(9);
            soma = 0;
            for (i = 10; i > 1; i--)
                soma += numeros.charAt(10 - i) * i;
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
            if (resultado != digitos.charAt(0))
                return false;
            numeros = cpf.substring(0,10);
            soma = 0;
            for (i = 11; i > 1; i--)
                soma += numeros.charAt(11 - i) * i;
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
            if (resultado != digitos.charAt(1))
                return false;
            return true;
        }
        else
            return false;
    },
    /*--------------------------------------------------------------------------*/
    Mascara:function(tipo, campo, teclaPress) {
        if (window.event)
        {
            var tecla = teclaPress.keyCode;
        } else {
            tecla = teclaPress.which;
        }

        var s = new String(campo.value);
        // Remove todos os caracteres à seguir: ( ) / - . e espaço, para tratar a string denovo.
        s = s.replace(/(\.|\(|\)|\/|\-| )+/g,'');

        tam = s.length + 1;

        if ( tecla!= 9 && tecla!= 11 && tecla != 8 && tecla!=13) {
            switch (tipo)
            {
                case 'CPF' :
                    if (tam > 3 && tam < 7)
                        campo.value = s.substr(0,3) + '.' + s.substr(3, tam);
                    if (tam >= 7 && tam < 10)
                        campo.value = s.substr(0,3) + '.' + s.substr(3,3) + '.' + s.substr(6,tam-6);
                    if (tam >= 10 && tam < 12)
                        campo.value = s.substr(0,3) + '.' + s.substr(3,3) + '.' + s.substr(6,3) + '-' + s.substr(9,tam-9);
                    break;

                case 'CNPJ' :

                    if (tam > 2 && tam < 6)
                        campo.value = s.substr(0,2) + '.' + s.substr(2, tam);
                    if (tam >= 6 && tam < 9)
                        campo.value = s.substr(0,2) + '.' + s.substr(2,3) + '.' + s.substr(5,tam-5);
                    if (tam >= 9 && tam < 13)
                        campo.value = s.substr(0,2) + '.' + s.substr(2,3) + '.' + s.substr(5,3) + '/' + s.substr(8,tam-8);
                    if (tam >= 13 && tam < 15)
                        campo.value = s.substr(0,2) + '.' + s.substr(2,3) + '.' + s.substr(5,3) + '/' + s.substr(8,4)+ '-' + s.substr(12,tam-12);
                    break;

                case 'CPF/CNPJ':
                    if (tam > 3 && tam < 7)
                        campo.value = s.substr(0,3) + '.' + s.substr(3, tam);
                    if (tam >= 7 && tam < 10)
                        campo.value = s.substr(0,3) + '.' + s.substr(3,3) + '.' + s.substr(6,tam-6);
                    if (tam >= 10 && tam < 12)
                        campo.value = s.substr(0,3) + '.' + s.substr(3,3) + '.' + s.substr(6,3) + '-' + s.substr(9,tam-9);
                    if (tam >= 13 && tam < 14)
                        campo.value = s.substr(0,2) + '.' + s.substr(2,3) + '.' + s.substr(5,3) + '/' + s.substr(8,tam-8);
                    if (tam >= 13 && tam < 15)
                        campo.value = s.substr(0,2) + '.' + s.substr(2,3) + '.' + s.substr(5,3) + '/' + s.substr(8,4)+ '-' + s.substr(12,tam-12);

                    break;
                case 'TEL' :
                    if (tam > 2 && tam < 4)
                        campo.value = '(' + s.substr(0,2) + ') ' + s.substr(2,tam);
                    if (tam >= 7 && tam < 11)
                        campo.value = '(' + s.substr(0,2) + ') ' + s.substr(2,4) + '-' + s.substr(6,tam-6);
                    break;

                case 'DATA' :
                    if (tam > 2 && tam < 4)
                        campo.value = s.substr(0,2) + '/' + s.substr(2, tam);
                    if (tam > 4 && tam < 11)
                        campo.value = s.substr(0,2) + '/' + s.substr(2,2) + '/' + s.substr(4,tam-4);
                    break;
            }
        }
    }
    ,
    /*----------------------------------------------------------------------------*/
    MASCARA_MOEDA:function(objTextBox, SeparadorMilesimo, SeparadorDecimal, e){
        var sep = 0;
        var key = '';
        var i = j = 0;
        var len = len2 = 0;
        var strCheck = '0123456789';
        var aux = aux2 = '';
        var whichCode = (window.Event) ? e.which : e.keyCode;
        // 13=enter, 8=backspace as demais retornam 0(zero)
        // whichCode==0 faz com que seja possivel usar todas as teclas como delete, setas, etc
        if ((objTextBox.value.length >= objTextBox.maxLength) && (whichCode != 13) && (whichCode != 8)) whichCode = 1;
        if ((whichCode == 13) || (whichCode == 0) || (whichCode == 8))
            return true;
        key = String.fromCharCode(whichCode); // Valor para o código da Chave


        if (strCheck.indexOf(key) == -1)
            return false; // Chave inválida
        len = objTextBox.value.length;
        for(i = 0; i < len; i++)
            if ((objTextBox.value.charAt(i) != '0') && (objTextBox.value.charAt(i) != SeparadorDecimal))
                break;
        aux = '';
        for(; i < len; i++)
            if (strCheck.indexOf(objTextBox.value.charAt(i))!=-1)
                aux += objTextBox.value.charAt(i);
        aux += key;
        len = aux.length;
        if (len == 0)
            objTextBox.value = '';
        if (len == 1)
            objTextBox.value = '0'+ SeparadorDecimal + '0' + aux;
        if (len == 2)
            objTextBox.value = '0'+ SeparadorDecimal + aux;
        if (len > 2) {
            aux2 = '';
            for (j = 0, i = len - 3; i >= 0; i--) {
                if (j == 3) {
                    aux2 += SeparadorMilesimo;
                    j = 0;
                }
                aux2 += aux.charAt(i);
                j++;
            }
            objTextBox.value = '';
            len2 = aux2.length;
            for (i = len2 - 1; i >= 0; i--)
                objTextBox.value += aux2.charAt(i);
            objTextBox.value += SeparadorDecimal + aux.substr(len - 2, len);
        }
        return false;
    }
    ,
    /*----------------------------------------------------------------------------*/
    isIntegerInRange:function(n,Nmin,Nmax){
        var num = Number(n);
        if(isNaN(num)){
            return false;
        }
        if(num != Math.round(num)){
            return false;
        }
        return (num >= Nmin && num <= Nmax);
    },
    /*--------------------------------------------------------------------------*/
    isNum:function(number){
        numRegExp = /^[0-9]+$/
        return numRegExp.test(number);
    },
    /*--------------------------------------------------------------------------*/
    isEMailAddr:function(string){
        emailRegExp = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.([a-z]){2,4})$/
        return emailRegExp.test(string);
    },
    /*--------------------------------------------------------------------------*/
    isZipCode:function(zipcode,country){
        if(!zipcode) return false;
        if(!country) format = 'US';
        switch(country){
            case'US': zpcRegExp = /^\d{5}$|^\d{5}-\d{4}$/; break;
            case'MA': zpcRegExp = /^\d{5}$/; break;
            case'CA': zpcRegExp = /^[A-Z]\d[A-Z] \d[A-Z]\d$/; break;
            case'DU': zpcRegExp = /^[1-9][0-9]{3}\s?[a-zA-Z]{2}$/; break;
            case'FR': zpcRegExp = /^\d{5}$/; break;
            case'Monaco':zpcRegExp = /^(MC-)\d{5}$/; break;
        }
        return zpcRegExp.test(zipcode);
    },
    /*--------------------------------------------------------------------------*/
    isDate:function(date,format){
        var dia = date.substring(0,2);
        var mes = date.substring(3,5);
        var ano = date.substring(6,10);
        var hoje=new Date();
        if ((ano <= hoje.getFullYear())){
            switch(mes)
            {
                case '01':
                case '03':
                case '05':
                case '07':
                case '08':
                case '10':
                case '12':
                    if (dia <= 31)
                    {
                        return true;
                    }
                    break

                case '04':
                case '06':
                case '09':
                case '11':
                    if (dia <= 30)
                    {
                        return true;
                    }
                    break
                case '02':

                    var bissexto;

                    /* Validando ano Bissexto / fevereiro / dia */
                    if ((ano % 4 == 0) || (ano % 100 == 0) || (ano % 400 == 0))
                    {
                        bissexto = 1;
                    }
                    if ((bissexto == 1) && (dia <= 29))
                    {
                        return true;
                    }
                    if ((bissexto != 1) && (dia <= 28))
                    {
                        return true;
                    }
                    break;
            }
        }

        return false;
    },
    /*--------------------------------------------------------------------------*/
    isDateNascimento:function(date){
        var dia = date.substring(0,2);
        var mes = date.substring(3,5);
        var ano = date.substring(6,10);
        var hoje=new Date();
        if ((ano > 1900)&&(ano <= hoje.getFullYear()-18)){
            switch(mes)
            {
                case '01':
                case '03':
                case '05':
                case '07':
                case '08':
                case '10':
                case '12':
                    if (dia <= 31)
                    {
                        return true;
                    }
                    break

                case '04':
                case '06':
                case '09':
                case '11':
                    if (dia <= 30)
                    {
                        return true;
                    }
                    break
                case '02':

                    var bissexto;

                    /* Validando ano Bissexto / fevereiro / dia */
                    if ((ano % 4 == 0) || (ano % 100 == 0) || (ano % 400 == 0))
                    {
                        bissexto = 1;
                    }
                    if ((bissexto == 1) && (dia <= 29))
                    {
                        return true;
                    }
                    if ((bissexto != 1) && (dia <= 28))
                    {
                        return true;
                    }
                    break;
            }
        }

        return false;
    },
    /*--------------------------------------------------------------------------*/
    isDateExpiracao:function(date){
        var dia = date.substring(0,2);
        var mes = date.substring(3,5);
        var ano = date.substring(6,10);
        var hoje=new Date();
        if ((ano==hoje.getFullYear()) && (mes > hoje.getMonth())&&(mes < hoje.getMonth()+3)){
            if(mes==hoje.getMonth()+1 && (dia < hoje.getDate())){
                return false;
            }
            if(mes==hoje.getMonth()+2 && (dia > hoje.getDate())){
                return false;
            }
            switch(mes)
            {
                case '01':
                case '03':
                case '05':
                case '07':
                case '08':
                case '10':
                case '12':
                    if (dia <= 31)
                    {
                        return true;
                    }
                    break

                case '04':
                case '06':
                case '09':
                case '11':
                    if (dia <= 30)
                    {
                        return true;
                    }
                    break
                case '02':

                    var bissexto;

                    /* Validando ano Bissexto / fevereiro / dia */
                    if ((ano % 4 == 0) || (ano % 100 == 0) || (ano % 400 == 0))
                    {
                        bissexto = 1;
                    }
                    if ((bissexto == 1) && (dia <= 29))
                    {
                        return true;
                    }
                    if ((bissexto != 1) && (dia <= 28))
                    {
                        return true;
                    }
                    break;
            }
        }

        return false;
    },
    /*--------------------------------------------------------------------------*/
    isMD5:function(string){
        if(!string) return false;
        md5RegExp = /^[a-f0-9]{32}$/;
        return md5RegExp.test(string);
    },
    /*--------------------------------------------------------------------------*/
    isURL:function(string){
        if(!string) return false;
        string = string.toLowerCase();
        urlRegExp = /^(((ht|f)tp(s?))\:\/\/)([0-9a-zA-Z\-]+\.)+[a-zA-Z]{2,6}(\:[0-9]+)?(\/\S*)?$/
        return urlRegExp.test(string);
    },
    /*--------------------------------------------------------------------------*/
    isGuid:function(guid){//guid format : xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx or xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
        if(!guid) return false;
        GuidRegExp = /^[{|\(]?[0-9a-fA-F]{8}[-]?([0-9a-fA-F]{4}[-]?){3}[0-9a-fA-F]{12}[\)|}]?$/
        return GuidRegExp.test(guid);
    },
    /*--------------------------------------------------------------------------*/
    isISBN:function(number){
        if(!number) return false;
        ISBNRegExp = /ISBN\x20(?=.{13}$)\d{1,5}([- ])\d{1,7}\1\d{1,6}\1(\d|X)$/
        return ISBNRegExp.test(number);
    },
    /*--------------------------------------------------------------------------*/
    isSSN:function(number){//Social Security Number format : NNN-NN-NNNN
        if(!number) return false;
        ssnRegExp = /^\d{3}-\d{2}-\d{4}$/
        return ssnRegExp.test(number);
    },
    /*--------------------------------------------------------------------------*/
    isDecimal:function(number){// positive or negative decimal
        if(!number) return false;
        decimalRegExp = /^-?(0|[1-9]{1}\d{0,})(\.(\d{1}\d{0,}))?$/
        return decimalRegExp.test(number);
    },
    /*--------------------------------------------------------------------------*/
    isplatform:function(platform){
        //win, mac, nix
        if(!platform) return false;
        var os;
        winRegExp = /\win/i
        if(winRegExp.test(window.navigator.platform)) os = 'win';
		
        macRegExp = /\mac/i
        if(macRegExp.test(window.navigator.platform)) os = 'mac';
		
        nixRegExp = /\unix|\linux|\sun/i
        if(nixRegExp.test(window.navigator.platform)) os = 'nix';
		
        if(platform == os) return true;
        else return false;
    },
    /*--------------------------------------------------------------------------*/
    getValue:function(id){
        document.getElementById(id).value;
    },
    /*--------------------------------------------------------------------------*/
    addRules:function(rules){
        this.rules_array.push(rules);
    },
    /*--------------------------------------------------------------------------*/
    check:function(){
        this.error_array = [];
        this.e = true;
        for(var i=0;i<this.rules_array.length;i++){
            switch(this.rules_array[i].option){
                case 'isChars':
                    if(!this.isChars(getValue(this.rules_array[i].id))){
                        this.error_array.push(this.rules_array[i].error);
                        this.e = false;
                    }
                    break;
                /*--------------------------------------------------------------------------*/
                case 'isDateNascimento':
                    if(!this.isDateNascimento(getValue(this.rules_array[i].id))){
                        this.error_array.push(this.rules_array[i].error);
                        this.e = false;
                    }
                    break;
                /*--------------------------------------------------------------------------*/
                case 'isDateExpiracao':
                    if(!this.isDateExpiracao(getValue(this.rules_array[i].id))){
                        this.error_array.push(this.rules_array[i].error);
                        this.e = false;
                    }
                    break;
                /*--------------------------------------------------------------------------*/
                case 'iscpf':
                    if(!this.iscpf(getValue(this.rules_array[i].id))){
                        this.error_array.push(this.rules_array[i].error);
                        this.e = false;
                    }
                    break;
                /*--------------------------------------------------------------------------*/
                case 'iscnpj':
                    if(!this.iscnpj(getValue(this.rules_array[i].id))){
                        this.error_array.push(this.rules_array[i].error);
                        this.e = false;
                                       
                    }
                    break;
                /*--------------------------------------------------------------------------*/
                case 'iscnpj_cpf':
                    if(!this.iscnpj(getValue(this.rules_array[i].id)) && !this.iscpf(getValue(this.rules_array[i].id))){
                        this.error_array.push(this.rules_array[i].error);
                        this.e = false;
                                       
                    }
                    break;
                /*--------------------------------------------------------------------------*/
                case'ValidChars':
                    if(!this.hasValidChars(getValue(this.rules_array[i].id),this.rules_array[i].chars,false)){
                        this.error_array.push(this.rules_array[i].error);
                        this.e = false;
                    }
                    break;
                /*--------------------------------------------------------------------------*/
                case'AlphaLatin':
                    if (this.isAlphaLatin(getValue(this.rules_array[i].id))){
                        this.error_array.push(this.rules_array[i].error);
                        this.e = false;
                    }
                    break;
                /*--------------------------------------------------------------------------*/
                case'required':
                    if (this.isEmpty(getValue(this.rules_array[i].id))){
                        this.error_array.push(this.rules_array[i].error);
                        this.e = false;
                    }
                    break;
                /*--------------------------------------------------------------------------*/
                case'integerRange':
                    if (!this.isIntegerInRange(getValue(this.rules_array[i].id),this.rules_array[i].Min,this.rules_array[i].Max)){
                        this.error_array.push(this.rules_array[i].error);
                        this.e = false;
                    }
                    break;
                /*--------------------------------------------------------------------------*/
                case'Number':
                    if (!this.isNum(getValue(this.rules_array[i].id))){
                        this.error_array.push(this.rules_array[i].error);
                        this.e = false;
                    }
                    break;
                /*--------------------------------------------------------------------------*/
                case'email':
                    if (!this.isEMailAddr(getValue(this.rules_array[i].id))){
                        this.error_array.push(this.rules_array[i].error);
                        this.e = false;
                    }
                    break;
                /*--------------------------------------------------------------------------*/
                case'zipCode':
                    if (!this.isZipCode(getValue(this.rules_array[i].id),this.rules_array[i].country)){
                        this.error_array.push(this.rules_array[i].error);
                        this.e = false;
                    }
                    break;
                /*--------------------------------------------------------------------------*/
                case'isDate':
                    if(!this.isDate(getValue(this.rules_array[i].id))){
                        this.error_array.push(this.rules_array[i].error);
                        this.e = false;
                    }
                    break;
                /*--------------------------------------------------------------------------*/
                case'url':
                    if(!this.isURL(getValue(this.rules_array[i].id))){
                        this.error_array.push(this.rules_array[i].error);
                        this.e = false;
                    }
                    break;
                /*--------------------------------------------------------------------------*/
                case'Decimal':
                    if(!this.isDecimal(getValue(this.rules_array[i].id))){
                        this.error_array.push(this.rules_array[i].error);
                        this.e = false;
                    }
                    break;
                /*--------------------------------------------------------------------------*/
                case'isEqual':
                    if(!this.isEqual(getValue(this.rules_array[i].id),getValue(this.rules_array[i].to))){
                        this.error_array.push(this.rules_array[i].error);
                        this.e = false;
                    }
                    break;
                /*--------------------------------------------------------------------------*/
                case 'isPass':
                    if(!this.isPass(getValue(this.rules_array[i].id))){
                        this.error_array.push(this.rules_array[i].error);
                        this.e = false;
                    }
                    break;
                case 'isLogin':
                    if(!this.isLogin(getValue(this.rules_array[i].id))){
                        this.error_array.push(this.rules_array[i].error);
                        this.e = false;
                    }
                    break;
                /*--------------------------------------------------------------------------*/
                                
            }
        }
    },
    /*--------------------------------------------------------------------------*/
    Apply:function(el){
        this.check();
        if(this.e){
            return true;
        }else{
            var endMsg = this.error_array;
            if(!el){
                alert('Atenção ao preenchimento dos seguintes campos:\n\n'+this.error_array.toString().replace(/\,/gi,"\n"));
            }else{
                document.getElementById(el).innerHTML ='<b>Observe o preenchimento dos seguintes campos:</b><br/>'+ this.error_array.toString().replace(/\,/gi,"<br/>");
            }
            return false;
        }
    }
/*--------------------------------------------------------------------------*/
}

