//Validação de Formulario de cadastro

function loginSubmit(form){

	if (form.login.value.length == 0 || form.password.value.length == 0){
		alert('Por favor entre com Login e senha.');
		return false;
	}

	form.password.value = hex_md5(form.password.value);
	
	return true;
}

function validateCNPJ(fld){
	
	//Dar trim
	fld.value = trim(fld.value);
	
	var valid = validaCNPJ(fld.value);

	var img = document.getElementById('imgCNPJ');
	
	if (valid){
		img.src = 'images/icons/valid.gif';
	}else{
		img.src = 'images/icons/invalid.gif';
	}
}

function validaTextos(theForm){
	
	//Validar area
     if ( theForm.idarea.value.length == 0) {
      alert( 'Por favor escolha uma área.' );
      theForm.idarea.focus();
      return false;
    }
	//Validar texto
	if ( theForm.text.value.length == 0) {
      alert( 'Por favor digite um texto.' );
      theForm.idarea.focus();
      return false;
    }
	
	return true;
}

function validaNoticias(theForm){
	
	//Validar data
    if ( theForm.data.value == 'DD/MM/AAAA' ) {
      alert( 'Por favor informe a data.' );
      theForm.nascimento.focus();
      return false;
    }
    if ( !check_date(theForm.data)) {
      alert( 'Data inválida, por favor preencha no formato DD/MM/AAAA.' );
      theForm.nascimento.focus();
      return false;
    }
	//Validar chamada
	if ( theForm.chamada.value.length == 0) {
      alert( 'Por favor digite uma chamada.' );
      theForm.chamada.focus();
      return false;
    }
	//Validar texto
	if ( theForm.conteudo.value.length == 0) {
      alert( 'Por favor digite um texto.' );
      theForm.conteudo.focus();
      return false;
    }
	
	return true;
}

function validaProdutos(theForm){
	
	//Validar nome
     if ( theForm.pnome.value.length == 0) {
      alert( 'Por favor digite um nome.' );
      theForm.pnome.focus();
      return false;
    }
	//Validar link
	if ( theForm.plink.value.length == 0) {
      alert( 'Por favor forneça o link.' );
      theForm.plink.focus();
      return false;
    }
	//Validar categoria
	if ( theForm.pcategoria.value.length == 0) {
      alert( 'Por favor escolha uma categoria.' );
      theForm.pcategoria.focus();
      return false;
    }
	
	return true;
}

function validaClientes(theForm){
	
	//Validar CNPJ
     if ( theForm.cnpj.value.length == 0) {
      alert( 'Por favor digite o CNPJ.' );
      theForm.cnpj.focus();
      return false;
    }
     if ( !validaCNPJ(theForm.cnpj.value)) {
      alert( 'CNPJ inválido.' );
      theForm.cnpj.focus();
      return false;
    }

	//Validar Razão Social
	if ( theForm.razaosocial.value.length == 0) {
      alert( 'Por favor digite a Razão Social.' );
      theForm.razaosocial.focus();
      return false;
    }
	//Validar nome fantasia
	if ( theForm.nfantasia.value.length == 0) {
      alert( 'Por favor digite o Nome Fantasia.' );
      theForm.nfantasia.focus();
      return false;
    }
	//Validar técnico
	if ( theForm.tec_idusers.value.length == 0) {
      alert( 'Por favor escolha um Técnico Responsável.' );
      theForm.tec_idusers.focus();
      return false;
    }
	//Validar P. Atendimento
	if ( theForm.serviceplan.value.length == 0) {
      alert( 'Por favor escolha o Plano de Serviço.' );
      theForm.serviceplan.focus();
      return false;
    }
	//Validar cep
	if ( theForm.cep.value.length == 0) {
      alert( 'Por favor informe o cep.' );
      theForm.cep.focus();
      return false;
    }
	//Validar endereço
	if ( theForm.endereco.value.length == 0) {
      alert( 'Por favor informe o endereço.' );
      theForm.endereco.focus();
      return false;
    }
	//Validar cidade
	if ( theForm.cidade.value.length == 0) {
      alert( 'Por favor informe a cidade.' );
      theForm.cidade.focus();
      return false;
    }
	//Validar bairro
	if ( theForm.bairro.value.length == 0) {
      alert( 'Por favor informe o bairro.' );
      theForm.bairro.focus();
      return false;
    }
	//Validar Estado
	if ( theForm.estado.value.length == 0) {
      alert( 'Por favor escolha um estado.' );
      theForm.estado.focus();
      return false;
    }
	//Validar kmsede
	if ( theForm.kmsede.value.length == 0) {
      alert( 'Por favor informe a distância até a sede desta empresa.' );
      theForm.kmsede.focus();
      return false;
    }
	//Validar fone
	if ( theForm.fone.value.length == 0) {
      alert( 'Por favor informe o telefone.' );
      theForm.fone.focus();
      return false;
    }
	//Validar contatos
	if ( document.getElementsByClassName("useritem").length == 0) {
      alert( 'Por favor cadastre um contato.' );
      return false;
    }	

	return true;
}

function validaServicos(theForm){
	
	//Validar nome
     if ( theForm.snome.value.length == 0) {
      alert( 'Por favor digite um nome.' );
      theForm.snome.focus();
      return false;
    }
	//Validar link
	if ( theForm.sdesc.value.length == 0) {
      alert( 'Por favor digite a descrição.' );
      theForm.plink.focus();
      return false;
    }
	
	return true;
}

function validaFiles(theForm){
	
	//Validar nome
     if ( theForm.fnome.value.length == 0) {
      alert( 'Por favor digite um nome.' );
      theForm.fnome.focus();
      return false;
    }
	//Validar link
	if ( theForm.fperm.value.length == 0) {
      alert( 'Por favor escolha um tipo de permissão.' );
      theForm.fperm.focus();
      return false;
    }
	
	return true;
}


function validaContato(theForm){
	
	//Validar nome
     if ( theForm.nome.value.length == 0) {
      alert( 'Por favor digite um nome.' );
      theForm.nome.focus();
      return false;
    }
	
	//Validar email
	if ( theForm.email.value.length == 0) {
      alert( 'Por favor digite seu email.' );
      theForm.email.focus();
      return false;
    }else{
    	if ( !isEmail(theForm.email.value)) {
			alert("Endereço de email inválido!");
      		theForm.email.focus();
      		return false;
	    }	
	}
	
	//Validar assunto
	if ( theForm.assunto.value.length == 0) {
      alert( 'Por favor digite um assunto.' );
      theForm.assunto.focus();
      return false;
    }

	//Validar mensagem
	if ( theForm.mensagem.value.length == 0) {
      alert( 'Por favor digite uma mensagem.' );
      theForm.mensagem.focus();
      return false;
    }

	return true;
}










function validaAltSenha(theForm){


	//Valida Senha
     if ( theForm.newsenha.value.length == 0) {
      alert( 'Por favor digite uma senha.' );
      theForm.newsenha.focus();
      return false;
    }
     if ( theForm.newsenha.value.length < 6) {
      alert( 'Sua senha deve ter pelomenos 6 digitos.' );
      theForm.confsenha.value = '';
	  theForm.newsenha.focus();
      return false;
    }
     if ( theForm.newsenha.value != theForm.confsenha.value) {
      alert( 'As senhas não conferem' );
      theForm.newsenha.value = '';
	  theForm.confsenha.value = '';
	  theForm.newsenha.focus();
	  return false;
    }


	return true
}


function validaDadosPessoais(theForm){



	//Nome
     if ( theForm.usrnome.value.length == 0 ) {
      alert( 'Por favor digite seu Nome.' );
      theForm.usrnome.focus();
      return false;
    }

	//CPF
	if (!theForm.edit.value){
    	if ( theForm.cpf.value.length == 0 ) {
	      alert( 'Por favor digite CPF.' );
	      theForm.cpf.focus();
	      return false;
	    }
	}
	if (!theForm.edit.value){
		if ( !isCPF(theForm.cpf.value)) {
	 	  alert("CPF inválido!");
	      theForm.cpf.focus();
	      return false;
	    }
	}
	// Sexo
	if (!theForm.sexo[0].checked && !theForm.sexo[1].checked){
      alert( 'Por favor escolha um sexo.' );
      return false;
	}

	// Valida Email	
	if (!theForm.edit.value){
     if ( theForm.usremail.value.length == 0) {
      alert( 'Por favor digite um email.' );
      theForm.usremail.focus();
      return false;
    }
	}
	if (!theForm.edit.value){
     if ( !isEmail(theForm.usremail.value)) {
 	  alert("Endereço de email inválido!");
      theForm.usremail.focus();
      return false;
    }
	}
	if (!theForm.edit.value){
     if ( theForm.usremail.value != theForm.conf_email.value) {
      alert( 'Os emails não conferem' );
      theForm.usremail.value = '';
	  theForm.conf_email.value = '';
	  theForm.usremail.focus();
      return false;
    }
	}
	//Valida Nascimento
    if ( theForm.nascimento.value == 'DD/MM/AAAA' ) {
      alert( 'Por favor informe sua data de nascimento.' );
      theForm.nascimento.focus();
      return false;
    }
    if ( !check_date(theForm.nascimento)) {
      alert( 'Data de nascimento inválida, por favor preencha no formato DD/MM/AAAA.' );
      theForm.nascimento.focus();
      return false;
    }
	
	//Valida Bairro	
    if ( theForm.bairro.value.length == 0 ) {
      alert( 'Por favor escolha seu Bairro.' );
      theForm.bairro.focus();
      return false;
    }
	
	//Valida Estado	
    if ( theForm.estado.value.length == 0 ) {
      alert( 'Por favor escolha seu Estado.' );
      theForm.estado.focus();
      return false;
    }
	
	//Valida Pais	
    if ( theForm.pais.value.length == 0 ) {
      alert( 'Por favor escolha seu País.' );
      theForm.pais.focus();
      return false;
    }	

	//Valida Senha
	if (!theForm.edit.value){
	    if ( theForm.usrsenha.value.length == 0) {
	      alert( 'Por favor digite uma senha.' );
	      theForm.usrsenha.focus();
	      return false;
	    }
	}
	if (!theForm.edit.value){
	    if ( theForm.usrsenha.value.length < 6) {
	      alert( 'Sua senha deve ter pelomenos 6 digitos.' );
	      theForm.usrsenha.focus();
	      return false;
	    }
	}
	if (!theForm.edit.value){
	     if ( theForm.usrsenha.value != theForm.confsenha.value) {
	      alert( 'As senhas não conferem' );
	      theForm.usrsenha.value = '';
		  theForm.confsenha.value = '';
		  theForm.usrsenha.focus();
	      return false;
	    }
	}
/*	if (askTermos == 1){
		if (theForm.termosdeuso.checked == false){
	      alert( 'Você deve aceitar os Termos de Uso para efetivar seu cadastro.' );
	      theForm.termosdeuso.focus();
	      return false;
			
		}
	}
	*/
	return true
}


////////////////////////////
///// Funcoes de Validacao externas
///////////////////////////

function isEmail(incoming) {
	var emailstring = incoming;
	var ampIndex = emailstring.indexOf("@");
	var afterAmp = emailstring.substring((ampIndex + 1), emailstring.length);
	var dotIndex = afterAmp.indexOf(".");
	dotIndex = dotIndex + ampIndex + 1;
	afterAmp = emailstring.substring((ampIndex + 1), dotIndex);
	var afterDot = emailstring.substring((dotIndex + 1), emailstring.length);
	var beforeAmp = emailstring.substring(0,(ampIndex));
	var email_regex = /^\w(?:\w|-|\.(?!\.|@))*@\w(?:\w|-|\.(?!\.))*\.\w{2,3}/ 
	if ((emailstring.indexOf("@") != "-1") &&
		(emailstring.length > 5) &&
		(afterAmp.length > 0) &&
		(beforeAmp.length > 1) &&
		(afterDot.length > 1) &&
		(email_regex.test(emailstring)) ) {
		  return true;
	} else {
		return false;
	}
}

//////////////////
// Conjunto para verificação de CPF
/////////////////

//Verifica se string é numérica
function isNum(str)
{
      var VBlnIsNum;
      VIntTam = str.length;
      VBlnIsNum = true;
      if (VIntTam == 0)
      {
                  return false;
        }
      else
      {
                  for (i=0; i < VIntTam; i++)
                  {
                                 if (str.substring(i,i+1) < '0' || str.substring(i,i+1) > '9')
                                 {
                                             VBlnIsNum = false;
                                 }
                   }
                     return VBlnIsNum;
      }
}

//Função de validação de CPF
function isCPF(st) {
	if (st == "")
	  return (false);
	l = st.length;
	
	//aleterado para se usuário não digitar os zeros na frente do CPF, completar sozinho
	if ((l == 9) || (l == 8))
	{
				for (i = l ; i < 10; i++)
				{
							st = '0' + st
				}
	}
	l = st.length;
	st2 = "";
	for (i = 0; i < l; i++) {
	  caracter = st.substring(i,i+1);
	  if ((caracter >= '0') && (caracter <= '9'));
		 st2 = st2 + caracter;
	}
	if ((st2.length > 11) || (st2.length < 10))
	   return (false);
	if (st2.length==10)
	   st2 = '0' + st2;
	digito1 = st2.substring(9,10);
	digito2 = st2.substring(10,11);
	digito1 = parseInt(digito1,10);
	digito2 = parseInt(digito2,10);
	sum = 0; mul = 10;
	for (i = 0; i < 9 ; i++) {
		digit = st2.substring(i,i+1);
		tproduct = parseInt(digit ,10) * mul;
		sum += tproduct;
		mul--;
	}
	dig1 = ( sum % 11 );
	if ( dig1==0 || dig1==1 )
	   dig1=0;
	else
	  dig1 = 11 - dig1;
	if (dig1!=digito1)
	  return (false);
	sum = 0;
	mul = 11;
	for (i = 0; i < 10 ; i++) {
		digit = st2.substring(i,i+1);
		tproduct = parseInt(digit ,10)*mul;
		sum += tproduct;
		mul--;
	}
	dig2 = (sum % 11);
	if ( dig2==0 || dig2==1 )
	  dig2=0;
	else
	  dig2 = 11 - dig2;
	if (dig2 != digito2)
	  return (false);
	return (true);
}

function check_date(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) {
		  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 == 00) || (month == 00) || (year == 0000)) {
		  err = 1; 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("Date is incorrect!");
		  //DateField.select();
		  //DateField.focus();
		  return false;
	   }
}



// Exemplos de validações
/*
function validaCadastro(theForm,askTermos){
	
// Valida Nick	
     if ( theForm.usr_nick.value.length == 0 ) {
      alert( 'Por favor digite um nick.' );
      theForm.usr_nick.focus();
      return false;
    }
// Valida Senha
     if ( theForm.usr_senha.value.length == 0 ) {
      alert( 'Por favor digite uma senha.' );
      theForm.usr_senha.focus();
      return false;
    }

     if ( theForm.usr_senha.value.length < 6 ) {
      alert( 'Sua senha deve ter pelomenos 6 digitos.' );
      theForm.usr_senha.focus();
      return false;
    }
	
     if ( theForm.usr_senha.value != theForm.usr_senha2.value ) {
      alert( 'As senhas não conferem' );
      theForm.usr_senha.value = '';
	  theForm.usr_senha2.value = '';
	  theForm.usr_senha.focus();
      return false;
    }
// Valida Email	
     if ( theForm.usr_email.value.length == 0 ) {
      alert( 'Por favor digite um email.' );
      theForm.usr_email.focus();
      return false;
    }

     if ( !isEmail(theForm.usr_email.value) ) {
 	  alert("Endereço de email inválido!");
      theForm.usr_email.focus();
      return false;
    }
	
     if ( theForm.usr_email.value != theForm.usr_email2.value ) {
      alert( 'Os emails não conferem' );
      theForm.usr_email.value = '';
	  theForm.usr_email2.value = '';
	  theForm.usr_email.focus();
      return false;
    }

// Valida RG
     if ( theForm.usr_rg.value.length == 0 ) {
      alert( 'Por favor digite seu RG.\nCaso não possua um RG leia as instruções ao lado.' );
      theForm.usr_rg.focus();
      return false;
    }

     if ( theForm.usr_rg_oe.value.length == 0 ) {
      alert( 'Por favor digite o Orgão Emissor de seu RG.' );
      theForm.usr_rg_oe.focus();
      return false;
    }
	
	if (askTermos == 1){
		if (theForm.termosdeuso.checked == false){
	      alert( 'Você deve aceitar os Termos de Uso para efetivar seu cadastro.' );
	      theForm.termosdeuso.focus();
	      return false;
			
		}
	}
	
	return true
}

*/