	/* 	
		Este script JavaScript irá realizar validações em formulários 
		Walace Soares
		Livro PHP5
		(baseado no JavaScript mostrado no livro Crie um site B2C)
	*/
	
	// Esta é uma função simples para validar emails
	function valida_email(email) {
		var chars = "@#$&[]()/\\\{}!^:'\"";
		var pat=/^(.+)@(.+)$/;
		
		var emaildiv = email.match(pat);
		
		if(emaildiv==null)
			return false;
			
		var login = emaildiv[1];
		var dominio = emaildiv[2];
		
		for(var i=0;i<chars.length;i++) {
			if(login.indexOf(chars.substr(i,1))!=-1)
				return false;
		}
		
		for(var i=0;i<chars.length;i++) {
			if(dominio.indexOf(chars.substr(i,1))!=-1)
				return false;
		}
		
		return true;
	}
	
	// Valida uma string em particular (tipo login ou senha)
	function valida_string(string) {
		str = new String(string);
		if(str.length<3)
			return false;
		if(str.indexOf(" ")!=-1)
			return false;
	
		var chars = "@#$&[]()/\\\{}!^:'\"";
	
		for(var i=0;i<chars.length;i++) {
			if(str.indexOf(chars.substr(i,1))!=-1) {
				return false;
			}
		}
			
		return true;
	
	} 
	
	function valida_form(form,campos,nomescampos,tipos,status) {
		/*
		form = posição do formulário (0,1,...)
		campos = campos a verificar (0,1,2,...)
		tipos = tipo de cada campo:
					4-email
					8-string
					9-login/senha
					10-confirmação de senha 
		status = 0 - não obrigatório, 1 - obrigatório
		*/
	
		var mensagem = "Os seguintes campos estão incorretos\n\n";
		var erro = false;
		
		for(var i=0;i<campos.length;i++) {
			resultado=true;
			valor = document.forms[form].elements[campos[i]].value;
			switch(tipos[i]) {
			case 4:
				resultado = valida_email(valor);
				break;
			case 8:
			    if(status[i]<=1) {
				  resultado = (valor.length==0) ? false : true;
				}
				else {
				 resultado = (valor.length<status[i]) ? false : true;
				}
				break;
			case 9:
				resultado = valida_string(valor);
				break;
			case 10:
				resultado = valida_string(valor);
				if(resultado)
					resultado = (valor==document.forms[form].elements[campos[i-1]].value);
				break;
			}
			
			if(!resultado && (status[i]>=1 || (status[i]==0 && valor.length!=0))) {
				mensagem+= "- " + nomescampos[i] + "\n";
				erro = true;
			}
			
		}
	
		if(erro)
			alert(mensagem)
			
		return !erro;
	
	}


///////////////////////////////////////////////////////////////
// COLOCA SEMPRE NUMERO REAIS /////////////////////////////////
///////////////////////////////////////////////////////////////
    function demask(field, currency){
    var val2 = ''
    var strCheck = '0123456789';
    /*
    Se existe um elemento com o id=field, queremos o field.value
    Se não, queremos apenas a própria string contida em field
    */
    if (document.getElementById(field)){
	    valor = document.getElementById(field).value 
	    }else{
	    valor = field
    }
	    if (valor == ''){
		    return 0.00
		    }
		    for(z=0;z<valor.length;z++){
		     if (strCheck.indexOf(valor.charAt(z))!=-1) val2 += valor.charAt(z);
		    }
		    if (currency ==true){
	    parte1 = val2.substring(0,val2.length-2)
	    parte2 = val2.substring(val2.length-2)
	    returnvalue = parte1 + "." + parte2
	    return(returnvalue)
	    }
	    else{
	    return(val2)
	    }
    }

    function reais(obj,event){
    FormataReais(obj,'.',',',event)
    var whichCode = (window.Event) ? event.which : event.keyCode;
    if (whichCode == 8 && !document.all) {	
	    valor = obj.value	
	    x = valor.substring(0,valor.length-1)
	    y= demask(x,true)
	    z = formatCurrency(y)	
	    obj.value = z				
    }

    } // end function


    function backspace(obj,event){
    /*
    Essa função basicamente altera o  backspace nos input com máscara reais para os navegadores IE e opera.
    O IE não detecta o keycode 8 no evento keypress, por isso, tratamos no keydown.
    Como o opera suporta o infame document.all, tratamos dele na mesma parte do código.
    */
    var whichCode = (window.Event) ? event.which : event.keyCode;
    if (whichCode == 8 && document.all) {	
	    valor = obj.value	
	    var x = valor.substring(0,valor.length-1)
	    var y= demask(x,true)
	    var z = formatCurrency(y)	

	    obj.value=""
	    obj.value = z		
	    FormataReais(obj,'.',',',event)	
	    }// end if		
    }// end function

    function FormataReais(fld, milSep, decSep, 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;

    //if (whichCode == 8 ) return true; //backspace - estamos tratando disso em outra função no keydown
    if (whichCode == 0 ) return true;
    if (whichCode == 9 ) return true; //tecla tab
    if (whichCode == 13) return true; //tecla enter
    if (whichCode == 16) return true; //shift internet explorer
    if (whichCode == 17) return true; //control no internet explorer
    if (whichCode == 27 ) return true; //tecla esc
    if (whichCode == 34 ) return true; //tecla end
    if (whichCode == 35 ) return true; //tecla end
    if (whichCode == 36 ) return true; //tecla home

    if (e.preventDefault){ //standart browsers
		    e.preventDefault()
	    }else{ // internet explorer
		    e.returnValue = false
    }

    var key = String.fromCharCode(whichCode);  // Valor para o código da Chave
    if (strCheck.indexOf(key) == -1) return false;  // Chave inválida
    fld.value += key
    var len = fld.value.length;
    for(i = 0; i < len; i++)
	    if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;
    var aux = '';
    for(; i < len; i++){
	    if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);
    }
    len = aux.length;
    if (len == 0) fld.value = '';
    if (len == 1) fld.value = '0'+ decSep + '0' + aux;
    if (len == 2) fld.value = '0'+ decSep + aux;

    if (len > 2) {
    var aux2 = '';
    for (j = 0, i = len - 3; i >= 0; i--) {
    if (j == 3) {
    aux2 += milSep;
    j = 0;
    }
    aux2 += aux.charAt(i);
    j++;
    }
    fld.value = ''
    len2 = aux2.length;
    for (i = len2 - 1; i >= 0; i--)
    fld.value += aux2.charAt(i);
    fld.value += decSep + aux.substr(len - 2, len);
    }

      if (fld.createTextRange) {
        var range = fld.createTextRange();
        range.collapse(false);
        range.select();
      }
      else if (fld.setSelectionRange) {
        fld.focus();
        var length = fld.value.length;
        fld.setSelectionRange(length, length);
      }

    }

    function formatCurrency(num) {
	    num = num.toString().replace(/\$|\,/g,'');
	    if(isNaN(num))num = "0";
	    sign = (num == (num = Math.abs(num)));
	    num = Math.floor(num*100+0.50000000001);
	    cents = num%100;
	    num = Math.floor(num/100).toString();
	    if(cents<10)
	    cents = "0" + cents;
	    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	    num = num.substring(0,num.length-(4*i+3))+'.'+
	    num.substring(num.length-(4*i+3));
	    return (((sign)?'':'-') + num + ',' + cents);
    }
///////////////////////////////////////////////////////////////
// FIM NUMERO REAIS ///////////////////////////////////////////
///////////////////////////////////////////////////////////////
