/*
*/

//---------------------------------------------------------------------------------------


//------------------------------------
//http://elcio.com.br/ajax/mascara/
//------------------------------------

//http://logdaselva.com/mascara-de-cnpj-cpf-data-e-telefone-em-javascript/
function Mascara(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 != 8 ) {
		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 '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;
		}
	}
}

	var xmlhttp
	var bclienteexiste
	var sEmailAtencao

	var sTipo
	var o
		
//-------------------------------------------------		
	function FieldExist(campo, tipo){
		if (tipo=="email"){
			if (campo.value==campo.getAttribute('atual')) return true
			//document.getElementById('mens_email').style.display = "none"
		}
		if (tipo=="cpf"){
			if (campo.value==campo.getAttribute('atual')) return true
			//document.getElementById('mens_cpf').style.display = "none"
		}
		o = campo
		var bProcessa = true
		if(tipo=='email')
		{
			if (checa_email(campo.value) != ""){ 
				bProcessa = false
				document.getElementById('mens_email').innerHTML = checa_email(campo.value)
				document.getElementById('mens_email').style.display = "block"
			}
		}
		if(tipo=='cpf')
		{
			if (validacpf(campo) != ""){
				bProcessa = false
				document.getElementById('mens_cpf').innerHTML = validacpf(campo)
				document.getElementById('mens_cpf').style.display = "block"
			}
		}
		if(bProcessa)
		{
			sTipo = tipo
			GetXMLDoc ('ClienteAjax.asp?'+tipo+'=' + campo.value+'&data=' + Date());
		}
	}
		
	function GetXMLDoc(url)
	{
	xmlhttp=null
	// code for Mozilla, etc.
	if (window.XMLHttpRequest)
		{
		xmlhttp=new XMLHttpRequest()
		}
	// code for IE
	else if (window.ActiveXObject)
		{
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
		}
	if (xmlhttp!=null)
		{
		xmlhttp.onreadystatechange = state_IsChange
		xmlhttp.open("GET",url,false)
		xmlhttp.send(null)
		}
	else
		{
		alert("Seu browse não suporta XMLHTTP.")
		}
	}
//-------------------------------------------------		
	function state_IsChange()
	{
	// if xmlhttp shows "loaded"
	if (xmlhttp.readyState==4)
		{
		if (xmlhttp.status==200)
		{
			if (xmlhttp.responseText=="inexistente" ) {
				//alert("verdadeiro"+sTipo)
			} else {
				if (sTipo=="email")
				{
				document.getElementById('mens_email').innerHTML="Este email já existe em nossos cadastros...Verifique"
				document.getElementById('mens_email').style.display = "block"
				document.cadastro.clie_email.focus()
				}
				if (sTipo=="cpf")
				{
				document.getElementById('mens_cpf').innerHTML = "Este cpf já existe em nossos cadastros...Verifique"
				document.getElementById('mens_cpf').style.display = "block"
				}
				o.focus()
			}
		}
		else
		{
		alert("Ocorreu erro na recepção de dados:" + xmlhttp.statusText)
		}
		}
	}


//---------------------------------------------------------------------------------------

	function cepChange(){
		// document.cadastro.clie_estado.selectedIndex = document.cadastro.clie_cep.value.length;
		if (document.cadastro.clie_cep.value.length != 0){
			loadXMLDoc ('./CepAjax.asp?cep='+document.cadastro.clie_cep.value);
		}
	}

 function validacpf(Objcpf){
   //var cpf = document.cadastro.cpf.value;
		var msg = "";
		var cpf = Objcpf.value;
		exp = /\.|\-/g
		cpf = cpf.toString().replace( exp, "" );
   if(cpf.length != 11 || cpf == "00000000000" || cpf == "11111111111" ||
	  cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" ||
	  cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" ||
	  cpf == "88888888888" || cpf == "99999999999")
	 {
	  msg = "CPF inválido. Tente novamente."
	  return msg;
   }
   soma = 0;
   for(cc = 0; cc < 9; cc++)
   	 soma += parseInt(cpf.charAt(cc)) * (10 - cc);
   resto = 11 - (soma % 11);
   if(resto == 10 || resto == 11)
	 resto = 0;
   if(resto != parseInt(cpf.charAt(9)))
	 {
		 msg ="CPF inválido. Tente novamente.";
		 return msg;
   }
   soma = 0;
   for(cc = 0; cc < 10; cc ++)
	 soma += parseInt(cpf.charAt(cc)) * (11 - cc);
   resto = 11 - (soma % 11);
   if(resto == 10 || resto == 11)
	 resto = 0;
   if(resto != parseInt(cpf.charAt(10))){
		 msg ="CPF inválido. Tente novamente.";
		 return msg;
   }
   return msg;
 }

	function MascaraCnpj(Campo, teclapres){

   if(window.event){
    var tecla = teclapres.keyCode;
   }else  tecla = teclapres.which;

   var vr = new String(Campo.value);
   vr = vr.replace(".", "");
   vr = vr.replace(".", "");
   vr = vr.replace("/", "");
   vr = vr.replace("-", "");

   tam = vr.length + 1;
   
   if (tecla != 9 && tecla != 8){
      if (tam > 2 && tam < 6)
         Campo.value = vr.substr(0, 2) + '.' + vr.substr(2, tam);
      if (tam >= 6 && tam < 9)
         Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,tam-5);
      if (tam >= 9 && tam < 13)
         Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,3) + '/' + vr.substr(8,tam-8);
      if (tam >= 13 && tam < 15)
         Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,3) + '/' + vr.substr(8,4)+ '-' + vr.substr(12,tam-12);
      }
	}
	
	function validacnpj(ObjCnpj)
	{
		var msg = "";
		var cnpj = ObjCnpj.value;
		var valida = new Array(6,5,4,3,2,9,8,7,6,5,4,3,2);
		var dig1= new Number;
		var dig2= new Number;
		
		exp = /\.|\-|\//g
		cnpj = cnpj.toString().replace( exp, "" ); 
		if (cnpj=='00000000000000') {msg='CNPJ Invalido!'}
		var digito = new Number(eval(cnpj.charAt(12)+cnpj.charAt(13)));
				
		for(x = 0; x<valida.length; x++){
				dig1 += (x>0? (cnpj.charAt(x-1)*valida[x]):0);    
				dig2 += cnpj.charAt(x)*valida[x];    
		}
		dig1 = (((dig1%11)<2)? 0:(11-(dig1%11)));
		dig2 = (((dig2%11)<2)? 0:(11-(dig2%11)));
		
		if(((dig1*10)+dig2) != digito){msg = 'CNPJ Invalido!';}
		return msg;				
	}
	
	var xmlhttp
	
	function loadXMLDoc(url, tipo)
	{
	xmlhttp=null
	// code for Mozilla, etc.
	if (window.XMLHttpRequest)
		{
		xmlhttp=new XMLHttpRequest()
		}
	// code for IE
	else if (window.ActiveXObject)
		{
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
		}
	if (xmlhttp!=null)
		{
		xmlhttp.onreadystatechange = state_Change
		xmlhttp.open("GET",url,false)
		xmlhttp.send(null)
		}
	else
		{
		alert("Seu browse não suporta XMLHTTP.")
		}
	}

	function state_Change()
	{
	// if xmlhttp shows "loaded"
	if (xmlhttp.readyState==4)
		{
		if (xmlhttp.status==200)
		{
				if (xmlhttp.responseText=="" ) {
					document.cadastro.clie_estado.selectedIndex = 0; 
				} else {
				  for (loop=0; loop < document.cadastro.clie_estado.options.length; loop++)
						{
							if (document.cadastro.clie_estado.options[loop].value == xmlhttp.responseText){
								document.cadastro.clie_estado.selectedIndex = loop;
								break;
							}
						}

				}
		}
		else
		{
		alert("Ocorreu erro na recepção de dados:" + xmlhttp.statusText)
		}
		}
	}
	
//---------------------------------------------------------------------------------------
function CheckNumericKeyInfo( e )
{
e = e || window.event;
ch = e.which || e.keyCode;
if( ch != null) {
if( (ch >= 48 && ch <= 57)
|| ch == 0 || ch == 8 || ch == 9
|| ch == 13 ) return true;
}
alert('Por favor... Para este campo somente conteúdo numérico.');
return false;
}

	function isNumber(obj){ //obj -> Objeto do formulario.
		num="01213456789,";
		v=obj.value;
		for(i = 0; i <= v.length-1; i++){
			f = i + 1;
			s = v.substring(i, f);
			if (num.indexOf(s) < 0){
				//alert("Esse campo é numerico.");
				obj.value = obj.value.substring(0,i);
				obj.focus();
				return false;
			}
		}
			return true;
	}
				
	function SoNumeros(de, a){
		if (event.keyCode < (48 + de) || event.keyCode > (48 + a)) event.returnValue = false;
	}
				

function FormataReal(nvalor){
nvalor = nvalor.replace(".","");
nvalor = nvalor.replace(",",".");
return nvalor;
}
function FormataValor(objeto,teclapres,tammax,decimais) 
{
	var tecla			= teclapres.keyCode;
	var tamanhoObjeto	= objeto.value.length;
	if ((tecla == 8) && (tamanhoObjeto == tammax))
	{
		tamanhoObjeto = tamanhoObjeto - 1 ;
	}
    if (( tecla == 8 || tecla == 88 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ) && ((tamanhoObjeto+1) <= tammax))
	{
		vr	= objeto.value;
		vr	= vr.replace( "/", "" );
		vr	= vr.replace( "/", "" );
		vr	= vr.replace( ",", "" );
		vr	= vr.replace( ".", "" );
		vr	= vr.replace( ".", "" );
		vr	= vr.replace( ".", "" );
		vr	= vr.replace( ".", "" );
		tam	= vr.length;
		if (tam < tammax && tecla != 8)
		{
			tam = vr.length + 1 ;
		}
		if ((tecla == 8) && (tam > 1))
		{
			tam = tam - 1 ;
			vr = objeto.value;
			vr = vr.replace( "/", "" );
			vr = vr.replace( "/", "" );
			vr = vr.replace( ",", "" );
			vr = vr.replace( ".", "" );
			vr = vr.replace( ".", "" );
			vr = vr.replace( ".", "" );
			vr = vr.replace( ".", "" );
		}
		if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 )
		{
			if (decimais > 0)
			{
				if ( (tam <= decimais) )
				{ 
					objeto.value = ("0," + vr) ;
				}
				if( (tam == (decimais + 1)) && (tecla == 8))
				{
					objeto.value = vr.substr( 0, (tam - decimais)) + ',' + vr.substr( tam - (decimais), tam ) ;	
				}
				if ( (tam > (decimais + 1)) && (tam <= (decimais + 3)) &&  ((vr.substr(0,1)) == "0"))
				{
					objeto.value = vr.substr( 1, (tam - (decimais+1))) + ',' + vr.substr( tam - (decimais), tam ) ;
				}
				if ( (tam > (decimais + 1)) && (tam <= (decimais + 3)) &&  ((vr.substr(0,1)) != "0"))
				{
				    objeto.value = vr.substr( 0, tam - decimais ) + ',' + vr.substr( tam - decimais, tam ) ; 
				}
				if ( (tam >= (decimais + 4)) && (tam <= (decimais + 6)) )
				{
			 		objeto.value = vr.substr( 0, tam - (decimais + 3) ) + '.' + vr.substr( tam - (decimais + 3), 3 ) + ',' + vr.substr( tam - decimais, tam ) ;
				}
			 	if ( (tam >= (decimais + 7)) && (tam <= (decimais + 9)) )
				{
			 		objeto.value = vr.substr( 0, tam - (decimais + 6) ) + '.' + vr.substr( tam - (decimais + 6), 3 ) + '.' + vr.substr( tam - (decimais + 3), 3 ) + ',' + vr.substr( tam - decimais, tam ) ;
				}
				if ( (tam >= (decimais + 10)) && (tam <= (decimais + 12)) )
				{
			 		objeto.value = vr.substr( 0, tam - (decimais + 9) ) + '.' + vr.substr( tam - (decimais + 9), 3 ) + '.' + vr.substr( tam - (decimais + 6), 3 ) + '.' + vr.substr( tam - (decimais + 3), 3 ) + ',' + vr.substr( tam - decimais, tam ) ;
				}
				if ( (tam >= (decimais + 13)) && (tam <= (decimais + 15)) )
				{
			 		objeto.value = vr.substr( 0, tam - (decimais + 12) ) + '.' + vr.substr( tam - (decimais + 12), 3 ) + '.' + vr.substr( tam - (decimais + 9), 3 ) + '.' + vr.substr( tam - (decimais + 6), 3 ) + '.' + vr.substr( tam - (decimais + 3), 3 ) + ',' + vr.substr( tam - decimais, tam ) ;
				}
			}
			else if(decimais == 0)
			{
				if ( tam <= 3 )
				{ 
			 		objeto.value = vr ;
				}
				if ( (tam >= 4) && (tam <= 6) )
				{
					if(tecla == 8)
					{
						objeto.value = vr.substr(0, tam);
						window.event.cancelBubble = true;
						window.event.returnValue = false;
					}
					objeto.value = vr.substr(0, tam - 3) + '.' + vr.substr( tam - 3, 3 ); 
				}
				if ( (tam >= 7) && (tam <= 9) )
				{
					if(tecla == 8)
					{
						objeto.value = vr.substr(0, tam);
						window.event.cancelBubble = true;
						window.event.returnValue = false;
					}
					objeto.value = vr.substr( 0, tam - 6 ) + '.' + vr.substr( tam - 6, 3 ) + '.' + vr.substr( tam - 3, 3 ); 
				}
				if ( (tam >= 10) && (tam <= 12) )
				{
			 		if(tecla == 8)
					{
						objeto.value = vr.substr(0, tam);
						window.event.cancelBubble = true;
						window.event.returnValue = false;
					}
					objeto.value = vr.substr( 0, tam - 9 ) + '.' + vr.substr( tam - 9, 3 ) + '.' + vr.substr( tam - 6, 3 ) + '.' + vr.substr( tam - 3, 3 ); 
				}

				if ( (tam >= 13) && (tam <= 15) )
				{
					if(tecla == 8)
					{
						objeto.value = vr.substr(0, tam);
						window.event.cancelBubble = true;
						window.event.returnValue = false;
					}
					objeto.value = vr.substr( 0, tam - 12 ) + '.' + vr.substr( tam - 12, 3 ) + '.' + vr.substr( tam - 9, 3 ) + '.' + vr.substr( tam - 6, 3 ) + '.' + vr.substr( tam - 3, 3 ) ;
				}			
			}
		}
	}
	else if((window.event.keyCode != 8) && (window.event.keyCode != 9) && (window.event.keyCode != 13) && (window.event.keyCode != 35) && (window.event.keyCode != 36) && (window.event.keyCode != 46))
		{
			window.event.cancelBubble = true;
			window.event.returnValue = false;
		}
}

function abre_janela(width, height, nome) {
var top; var left;
top = ( (screen.height/2) - (height/2) )
left = ( (screen.width/2) - (width/2) )
window.open('',nome,'width='+width+',height='+height+',scrollbars=yes,toolbar=no,location=no,status=no,menubar=no,resizable=no,left='+left+',top='+top);
}
function recebe_imagem(campo, imagem){
var foto = 'img_' + campo
document.form_alterar[campo].value = imagem;
document.form_alterar[foto].src = imagem;
}

function verifica_form(form) {
	var passed = false;
	var ok = false
	var campo
	for (i = 0; i < form.length; i++) {
		campo = form[i].name;
		//alert(campo+"-"+form[i].type+"-"+form[i].value+"-df_verificar-"+form[i].getAttribute('df_verificar'));
		if (form[i].getAttribute('df_verificar') == "sim") {
			if (form[i].type == "text"  | form[i].type == "textarea" | form[i].type == "select-one" | form[i].type == "password") {
				if (form[i].value == "" | form[i].value == "http://") {
					form[campo].className='campo_alerta'
					var mensagem = "Preencha corretamente o campo."
					alert(mensagem);
					form[campo].focus();
					return false;
					stop;
				}
				var msg = ""
				//if (form[campo].df_validar == "cpf") msg = checa_cpf(form[campo].value);
				if (form[campo].getAttribute('df_validar') == "cpf")
				{
					msg = validacpf(form[campo]);
					if(document.getElementById('mens_cpf').style.display == "block")
					{
						msg = 'Verifique ocorrência de erro no Cpf.'
					}
				}
				if (form[i].type == "select-one"){
					var selIndex = form[i].selectedIndex;
					if (selIndex==0) msg='Selecione...'
					if (form[i].options[selIndex].value=='') msg='Selecione...'
				}
					
				if (form[campo].getAttribute('df_validar') == "cnpj") msg = validacnpj(form[campo]);
				if (form[campo].getAttribute('df_validar') == "email")
				{
					msg = checa_email(form[campo].value)  //verifica formato
					if (msg=='' && form[campo].value!=form[campo].getAttribute('atual')){
						FieldExist(form[campo], 'email')
						alert(xmlhttp.responseText);
						if(xmlhttp.responseText=="existente")
						{
						form[campo].focus();
						return false;
						stop;
						}
					}
				}
				//if (form[campo].getAttribute('df_validar') == "numerico") msg = checa_numerico(form[campo].value);
				if (msg != "") {
					form[campo].className='campo_alerta'
					alert(msg);
					form[campo].focus();
					return false;
					stop;
				}
			}
		}
	}
	return true;
}

function desabilita_cor(campo) {
campo.className='caixa_normal'
}
function checa_numerico(String) {
var mensagem = "Este campo aceita somente números"
var msg = "";
if (isNaN(String)) msg = mensagem;
return msg;
}
function checa_email(campo) {
var mensagem = "Informe corretamente o email"
var msg = "";
var email = campo.match(/(\w+)@(.+)\.(\w+)$/);
if (email == null){
  msg = mensagem;
  }
return msg;
}

