/*
  -------------------------------------------------------------------------
  AGCORP Network - Varias funcoes de validacao de campos
  www.agcorp.net
  -------------------------------------------------------------------------  
*/

function FiltrarClientes( tipo )  //Filtra Planos em funcao do tipo selecionado
{
  http.open("GET", "filtrarclientes.php?tipo=" + tipo, true);
  http.onreadystatechange = handleHttpResponse;
  http.send(null);
}

function handleHttpResponse()
{
  if (http.readyState == 4) {
	
	  if (http.status == 200) {
		  	campo_select = document.forms[0].codcliente;
			campo_select.options.length = 0;
    		campo_select.options[0] = new Option( "SELECIONE",0);
			campo_select.options[0].select;

    		results = http.responseText.split(";");

			tot = results.length;
    		for( i = 0; i < tot-1; i++ )
    		{ 
      		string = results[i].split( "|" );
      		campo_select.options[i+1] = new Option( string[0], string[1] );
	  		}
	  } else {
		var div = document.getElementById("msg");
			div.innerHTML = "<font color=red>Houve um erro na solicitaçao. Tente mais tarde.</font>";
	  }
  }
}


function ValidaCPF(cpf) {

   var numero = cpf.value;
   erro = new String;
   numero = numero.replace("-","");
   numero = numero.replace(".","");
   numero = numero.replace(".","");
   if (numero.length < 11) 
   {
    erro = "O CPF deve conter 11 digitos.";
   }
   var nonNumbers = /\D/;
   if (nonNumbers.test(numero)) erro = "o CPF deve conter só números."; 
   if (numero == "00000000000" || numero == "11111111111" || numero == "22222222222" || numero == "33333333333" || numero == "44444444444" || numero == "55555555555" || numero == "66666666666" || numero == "77777777777" || numero == "88888888888" || numero == "99999999999")
   {
    erro = "Numero de CPF Invalido.";
   }
   var a = [];
   var b = new Number;
   var c = 11;
   for (i=0; i<11; i++)
   {
    a[i] = numero.charAt(i);
    if (i < 9) b += (a[i] * --c);
   }
   if ((x = b % 11) < 2)
   {
    a[9] = 0 
   }
   else
   {
    a[9] = 11-x 
   }
   b = 0;
   c = 11;
   for (y=0; y<10; y++) b += (a[y] * c--); 
   if ((x = b % 11) < 2)
   {
    a[10] = 0; } else { a[10] = 11-x;
   }
   if ((numero.charAt(9) != a[9]) || (numero.charAt(10) != a[10]))
   {
    erro ="Numero de CPF Invalido: " + numero;
   }
   if (erro.length > 0)
   {
       alert(erro);
	   cpf.click();
	   cpf.focus();
       return false;
   }
return true;   

}

function ValidaCNPJ(cnpj) {
	var numero = cnpj.value;
	erro = new String;
	//numero = numero.replace("-","");
	//numero = numero.replace(".","");
	//numero = numero.replace(".","");
	//numero = numero.replace("/","");
	
	CNPJ = numero;
	
     if (CNPJ.length < 18) erro += "É necessario preencher corretamente o número do CNPJ: "+CNPJ+"\n\n"; 
     if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")){
	   if (erro.length == 0) erro += "É necessário preencher corretamente o número do CNPJ: "+CNPJ+"\n\n";
	 }
     //substituir os caracteres que não são números
     if(document.layers && parseInt(navigator.appVersion) == 4){
        x = CNPJ.substring(0,2);
        x += CNPJ. substring (3,6);
        x += CNPJ. substring (7,10);
        x += CNPJ. substring (11,15);
        x += CNPJ. substring (16,18);
     CNPJ = x; 
     } else {
       CNPJ = CNPJ. replace (".","");
       CNPJ = CNPJ. replace (".","");
       CNPJ = CNPJ. replace ("-","");
       CNPJ = CNPJ. replace ("/","");
     }
     var nonNumbers = /\D/;
     if (nonNumbers.test(CNPJ)) erro += "A verificação de CNPJ suporta apenas números! \n\n"; 
        var a = [];
        var b = new Number;
        var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
        for (i=0; i<12; i++){
           a[i] = CNPJ.charAt(i);
           b += a[i] * c[i+1];
        }
     if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }
     b = 0;
     for (y=0; y<13; y++) {
        b += (a[y] * c[y]); 
     }
     if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11-x; }
     if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])){
       erro +="Dígito verificador com problema!";
     }
     if (erro.length > 0){
       alert(erro);
	   cnpj.click();
	   cnpj.focus();
	   
       return false;
     } else {
       return true;
     }
 return true;
}


//-----------------------------------------------------------------------------

function ValidaData(field)
{
var checkstr = "0123456789";
var DateField = field;
var Datevalue = "";
var DateTemp = "";
var seperator = "/";
var day;
var month;
var year;
var leap = 0;
var err = 0;
var i;
err = 0;
DateValue = DateField.value;
/* Delete all chars except 0..9 */
for (i = 0; i < DateValue.length; i++) {
if (checkstr.indexOf(DateValue.substr(i,1)) >= 0) {
DateTemp = DateTemp + DateValue.substr(i,1);
}
}
DateValue = DateTemp;
/* Always change date to 8 digits - string*/
/* if year is entered as 2-digit / always assume 20xx */
if (DateValue.length == 6) {
DateValue = DateValue.substr(0,4) + '20' + DateValue.substr(4,2); }
if (DateValue.length != 8) {
err = 19;}
/* year is wrong if year = 0000 */
year = DateValue.substr(4,4);

//if (year == 0 || year > 9999 || year <= 0000) {
if (year == 0 || year > 9999) {
err = 20;
}

if (year < 1900 || year > 2100) {
err = 20;	
}
/* Validation of month*/
month = DateValue.substr(2,2);
if ((month < 1) || (month > 12)) {
err = 21;
}
/* Validation of day*/
day = DateValue.substr(0,2);
if (day < 1) {
err = 22;
}
/* Validation leap-year / february / day */
if ((year % 4 == 0) || (year % 100 == 0) || (year % 400 == 0)) {
leap = 1;
}
if ((month == 2) && (leap == 1) && (day > 29)) {
err = 23;
}
if ((month == 2) && (leap != 1) && (day > 28)) {
err = 24;
}
/* Validation of other months */
if ((day > 31) && ((month == "01") || (month == "03") || (month == 
"05") || (month == "07") || (month == "08") || (month == "10") || (month 
== "12"))) {
err = 25;
}
if ((day > 30) && ((month == "04") || (month == "06") || (month == 
"09") || (month == "11"))) {
err = 26;
}
/* if 00 ist entered, no error, deleting the entry */
if ((day == 0) && (month == 0) && (year == 00)) {
err = 0; day = ""; month = ""; year = ""; seperator = "";
}
/* if no error, write the completed date to Input-Field (e.g. 
13.12.2001) */
if (err == 0) {
DateField.value = day + seperator + month + seperator + year;

return true;

}
/* Error-message if err != 0 */
else {
alert("Data inválida ou fora de intervalo permitido. Formato: dd/mm/aaaa");
DateField.select();
return false;
}
}

//----------------------------------------------------

function ValidaMoeda(campo){
	Moeda = /^(R\$\s?)?\d{1,3}(\.\d{3})*(\,\d{2})$/;
	if (campo.value=="" || !Moeda.test(campo.value) )
    {
        alert ("\nPor favor digite o valor no formato R$ 0.000,00");
		campo.focus();
		campo.select();
        return false;
    }
	
return true;	
}

//-------------------------------------------------------

function ValidaFiltroEmails(form) {
	
	marcado = -1
	for (i=0; i<form.filtro.length; i++) {
		if (form.filtro[i].checked) {
			marcado = i
			opcaoselecionada = form.filtro[i].value
		}
	}
	
	    if (marcado == -1) {
		 alert ("Escolha a Opção de Filtro");
		return false;
		}
		if (opcaoselecionada == "somente" && form.concurso.value=="")  
		{
        alert ("É preciso selecionar o concurso a ser filtrado!");
        return false;    
		}
		if (opcaoselecionada == "email" && form.email.value=="")  
		{
        alert ("É preciso digitar um email!");
        return false;    
		}
		if (opcaoselecionada == "email")  
		{
        var frmvalidator  = new Validator("filtroemail");
	    frmvalidator.addValidation("email","email","Digite um Email Válido!");
		}
		
		if (form.tituloemail.value =="")
		{
		alert ("Escreva o Título do Email!");
		form.tituloemail.focus();
        return false;    
		}
		if (form.corpoemail.value =="")
		{
		alert ("Escreva o Texto do Email!");
		form.corpoemail.focus();
        return false;    
		}

    return true;
	
}

// -------------------------------------------------------



function Validator(frmname)
{
  this.formobj=document.forms[frmname];
	if(!this.formobj)
	{
	  alert("BUG: nao pude pegar o objeto do formulario "+frmname);
		return;
	}
	if(this.formobj.onsubmit)
	{
	 this.formobj.old_onsubmit = this.formobj.onsubmit;
	 this.formobj.onsubmit=null;
	}
	else
	{
	 this.formobj.old_onsubmit = null;
	}
	this.formobj.onsubmit=form_submit_handler;
	this.addValidation = add_validation;
	this.setAddnlValidationFunction=set_addnl_vfunction;
	this.clearAllValidations = clear_all_validations;
}
function set_addnl_vfunction(functionname)
{
  this.formobj.addnlvalidation = functionname;
}
function clear_all_validations()
{
	for(var itr=0;itr < this.formobj.elements.length;itr++)
	{
		this.formobj.elements[itr].validationset = null;
	}
}
function form_submit_handler()
{
	for(var itr=0;itr < this.elements.length;itr++)
	{
		if(this.elements[itr].validationset &&
	   !this.elements[itr].validationset.validate())
		{
		  return false;
		}
	}
	if(this.addnlvalidation)
	{
	  str =" var ret = "+this.addnlvalidation+"()";
	  eval(str);
    if(!ret) return ret;
	}
	return true;
}
function add_validation(itemname,descriptor,errstr)
{
  if(!this.formobj)
	{
	  alert("BUG: o objetivo no formulario nao foi setado corretamente");
		return;
	}//if
	var itemobj = this.formobj[itemname];
  if(!itemobj)
	{
	  alert("BUG: Nao pude pegar o nome do objeto: "+itemname);
		return;
	}
	if(!itemobj.validationset)
	{
	  itemobj.validationset = new ValidationSet(itemobj);
	}
  itemobj.validationset.add(descriptor,errstr);
}
function ValidationDesc(inputitem,desc,error)
{
  this.desc=desc;
	this.error=error;
	this.itemobj = inputitem;
	this.validate=vdesc_validate;
}
function vdesc_validate()
{
 if(!V2validateData(this.desc,this.itemobj,this.error))
 {
    this.itemobj.focus();
		return false;
 }
 return true;
}
function ValidationSet(inputitem)
{
    this.vSet=new Array();
	this.add= add_validationdesc;
	this.validate= vset_validate;
	this.itemobj = inputitem;
}
function add_validationdesc(desc,error)
{
  this.vSet[this.vSet.length]= 
	  new ValidationDesc(this.itemobj,desc,error);
}
function vset_validate()
{
   for(var itr=0;itr<this.vSet.length;itr++)
	 {
	   if(!this.vSet[itr].validate())
		 {
		   return false;
		 }
	 }
	 return true;
}
function validateEmailv2(email)
{
// a very simple email validation checking. 
// you can add more complex email checking if it helps 
    if(email.length <= 0)
	{
	  return true;
	}
    var splitted = email.match("^(.+)@(.+)$");
    if(splitted == null) return false;
    if(splitted[1] != null )
    {
      var regexp_user=/^\"?[\w-_\.]*\"?$/;
      if(splitted[1].match(regexp_user) == null) return false;
    }
    if(splitted[2] != null)
    {
      var regexp_domain=/^[\w-\.]*\.[A-Za-z]{2,4}$/;
      if(splitted[2].match(regexp_domain) == null) 
      {
	    var regexp_ip =/^\[\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\]$/;
	    if(splitted[2].match(regexp_ip) == null) return false;
      }// if
      return true;
    }
return false;
}
function V2validateData(strValidateStr,objValue,strError) 
{ 
    var epos = strValidateStr.search("="); 
    var  command  = ""; 
    var  cmdvalue = ""; 
    if(epos >= 0) 
    { 
     command  = strValidateStr.substring(0,epos); 
     cmdvalue = strValidateStr.substr(epos+1); 
    } 
    else 
    { 
     command = strValidateStr; 
    } 
    switch(command) 
    { 
        case "req": 
        case "required": 
         { 
           if(eval(objValue.value.length) == 0) 
           { 
              if(!strError || strError.length ==0) 
              { 
                strError = objValue.name + " : Campo requerido"; 
              }//if 
              alert(strError); 
              return false; 
           }//if 
           break;             
         }//case required 
        case "maxlength": 
        case "maxlen": 
          { 
             if(eval(objValue.value.length) >  eval(cmdvalue)) 
             { 
               if(!strError || strError.length ==0) 
               { 
                 strError = objValue.name + " : "+cmdvalue+" caracteres máximos "; 
               }//if 
               alert(strError + "\n[Tamanho atual = " + objValue.value.length + " ]"); 
               return false; 
             }//if 
             break; 
          }//case maxlen 
        case "minlength": 
        case "minlen": 
           { 
             if(eval(objValue.value.length) <  eval(cmdvalue)) 
             { 
               if(!strError || strError.length ==0) 
               { 
                 strError = objValue.name + " : " + cmdvalue + " Caracteres mínimos  "; 
               }//if               
               alert(strError + "\n[Tamanho atual = " + objValue.value.length + " ]"); 
               return false;                 
             }//if 
             break; 
            }//case minlen 
        case "alnum": 
        case "alphanumeric": 
           { 
              var charpos = objValue.value.search("[^A-Za-z0-9]"); 
              if(objValue.value.length > 0 &&  charpos >= 0) 
              { 
               if(!strError || strError.length ==0) 
                { 
                  strError = objValue.name+": Só são permitidos letras e numeros "; 
                }//if 
                alert(strError + "\n [Erro de caractere na posicao " + eval(charpos+1)+"]"); 
                return false; 
              }//if 
              break; 
           }//case alphanumeric 
        case "num": 
        case "numeric": 
           { 
              var charpos = objValue.value.search("[^0-9]"); 
              if(objValue.value.length > 0 &&  charpos >= 0) 
              { 
                if(!strError || strError.length ==0) 
                { 
                  strError = objValue.name+": Somente numeros são permitidos "; 
                }//if               
                alert(strError + "\n [Erro de caractere na posicao " + eval(charpos+1)+"]"); 
                return false; 
              }//if 
              break;               
           }//numeric 
        case "alphabetic": 
        case "alpha": 
           { 
              var charpos = objValue.value.search("[^A-Za-z]"); 
              if(objValue.value.length > 0 &&  charpos >= 0) 
              { 
                  if(!strError || strError.length ==0) 
                { 
                  strError = objValue.name+": Somente caracteres alfabeticos são permitidos "; 
                }//if                             
                alert(strError + "\n [Erro de caractere na posicao " + eval(charpos+1)+"]"); 
                return false; 
              }//if 
              break; 
           }//alpha 
		case "alnumhyphen":
			{
              var charpos = objValue.value.search("[^A-Za-z0-9\-_]"); 
              if(objValue.value.length > 0 &&  charpos >= 0) 
              { 
                  if(!strError || strError.length ==0) 
                { 
                  strError = objValue.name+": só são permitidos caracteres de A-Z,a-z,0-9,- e _"; 
                }//if                             
                alert(strError + "\n [Erro de caractere na posicao " + eval(charpos+1)+"]"); 
                return false; 
              }//if 			
			break;
			}
        case "email": 
          { 
               if(!validateEmailv2(objValue.value)) 
               { 
                 if(!strError || strError.length ==0) 
                 { 
                    strError = objValue.name+": Entre com um endereco de email valido. "; 
                 }//if                                               
                 alert(strError); 
                 return false; 
               }//if 
           break; 
          }//case email 
        case "lt": 
        case "lessthan": 
         { 
            if(isNaN(objValue.value)) 
            { 
              alert(objValue.name+": Deveria ser um numero "); 
              return false; 
            }//if 
            if(eval(objValue.value) >=  eval(cmdvalue)) 
            { 
              if(!strError || strError.length ==0) 
              { 
                strError = objValue.name + " : O valor deveria ser menor que "+ cmdvalue; 
              }//if               
              alert(strError); 
              return false;                 
             }//if             
            break; 
         }//case lessthan 
        case "gt": 
        case "greaterthan": 
         { 
            if(isNaN(objValue.value)) 
            { 
              alert(objValue.name+": Deveria seru um numero "); 
              return false; 
            }//if 
             if(eval(objValue.value) <=  eval(cmdvalue)) 
             { 
               if(!strError || strError.length ==0) 
               { 
                 strError = objValue.name + " : O valor deveria ser maior que "+ cmdvalue; 
               }//if               
               alert(strError); 
               return false;                 
             }//if             
            break; 
         }//case greaterthan 
        case "regexp": 
         { 
		 	if(objValue.value.length > 0)
			{
	            if(!objValue.value.match(cmdvalue)) 
	            { 
	              if(!strError || strError.length ==0) 
	              { 
	                strError = objValue.name+": Caracteres invalidos encontrados "; 
	              }//if                                                               
	              alert(strError); 
	              return false;                   
	            }//if 
			}
           break; 
         }//case regexp 
        case "dontselect": 
         { 
            if(objValue.selectedIndex == null) 
            { 
              alert("BUG: dontselect command for non-select Item"); 
              return false; 
            } 
            if(objValue.selectedIndex == eval(cmdvalue)) 
            { 
             if(!strError || strError.length ==0) 
              { 
              strError = objValue.name+": Please Select one option "; 
              }//if                                                               
              alert(strError); 
              return false;                                   
             } 
             break; 
         }//case dontselect 
    }//switch 
    return true; 
}

//------------------------------------------------



function getHTTPObject() {
var req;

try {
 if (window.XMLHttpRequest) {
  req = new XMLHttpRequest();

  if (req.readyState == null) {
   req.readyState = 1;
   req.addEventListener("load", function () {
   req.readyState = 4;

   if (typeof req.onReadyStateChange == "function")
    req.onReadyStateChange();
   }, false);
  }

  return req;
 }

 if (window.ActiveXObject) {
  var prefixes = ["MSXML2", "Microsoft", "MSXML", "MSXML3"];

  for (var i = 0; i < prefixes.length; i++) {
   try {
    req = new ActiveXObject(prefixes[i] + ".XmlHttp");
    return req;
   } catch (ex) {};
  }
 }
} catch (ex) {}

alert("Objetos XmlHttp nao suportados por seu navegador - Nao e possivel usar AJAX aqui.");
}
var http = getHTTPObject();

// acrescimo por Abdenego Santos www.abdenego.com.br
