function retirarAcento(objResp) {  
	var varString = new String(objResp.value);  
    var stringAcentos = new String('àâêôûãõáéíóúçüÀÂÊÔÛÃÕÁÉÍÓÚÇÜ');  
    var stringSemAcento = new String('aaeouaoaeioucuAAEOUAOAEIOUCU');  
      
    var i = new Number();  
    var j = new Number();  
    var cString = new String();  
    var varRes = '';  
    
    for (i = 0; i < varString.length; i++) {  
   		cString = varString.substring(i, i + 1);  
   		for (j = 0; j < stringAcentos.length; j++) {  
   			if (stringAcentos.substring(j, j + 1) == cString){  
   				cString = stringSemAcento.substring(j, j + 1);  
   			}  
   		}  
   		varRes += cString;  
   	}  
   	objResp.value = varRes;  
}  

    
/*function bloquearControle(e) {

	//list all CTRL + key combinations you want to disable
    var forbiddenKeys = new Array('a', 'n', 'c', 'x', 'v', 'j');
    var key;
    var isCtrl;

    if(window.event) {
    	key = window.event.keyCode;     //IE
        if(window.event.ctrlKey)
        	isCtrl = true;
        else
        	isCtrl = false;
        }
        else{
            key = e.which;     //firefox
            if(e.ctrlKey)
            	isCtrl = true;
            else
                isCtrl = false;
        }

        //if ctrl is pressed check if other key is in forbidenKeys array
        if(isCtrl) {
        	for(i=0; i<forbiddenkeys.length; i++) {
            	//case-insensitive comparation
                if(forbiddenKeys[i].toLowerCase() == String.fromCharCode(key).toLowerCase()) {
                	alert('Key combination CTRL + '
                    +String.fromCharCode(key)
                    +' has been disabled.');
                    return false;
                }
            }
        }
        return true;
	}  */

// Popup de produtos para adicionar ao pedido atual
function popbusca(url, nome){
	var largura = 800;
	var altura  = 500;

	var t = (window.screen.height-altura)/2;
	var l = (window.screen.width-largura)/2;
	settings = 	'toolbar=no, location=no, directories=no, status=yes, menubar=no, scrollbars=yes, ';
	settings +=	'resizable=no,copyhistory=no,width='+largura+',height='+altura+',top='+t+',left='+l;

	popupWindow = window.open(url, nome, settings);
	popupWindow.focus();
}

//ADICIONA PRODUTO 
function adicionaProduto(id,nomeProduto,valor){
	opener.document.form_produto.id_produto.value	= id;
	opener.document.form_produto.nomeProduto.value  = nomeProduto;
	opener.document.form_produto.valor.value		= valor;
	window.close();
}


function moeda2float(moeda,nome){

	moeda = moeda.replace(".","");

	moeda = moeda.replace(",",".");

	document.getElementById(nome).value = parseFloat(moeda);

}

function acao(nome,valor){
    
    document.getElementById(nome).action = valor;
   
}

function verificaSenha() {
        
	senha1 = document.cadastro_cliente.senha.value;
    senha2 = document.cadastro_cliente.senha_confirmar.value;
        
    if(senha1 != senha2) {
    	alert("Senha não confere, por favor digite novamente");
        document.cadastro_cliente.senha_confirmar.value = "";
    }
}

function senhaValidada() {
        
	senha1 = document.cadastro_cliente.senha.value;
    senha2 = document.cadastro_cliente.senha_confirmar.value;
        
    if(senha1 != senha2) {
    	alert("Senha não confere, por favor digite novamente");
        document.cadastro_cliente.senha_confirmar.value = "";
        return false;
    }
    return true;
}

function validaEmail() {
        
	email  = document.cadastro_cliente.email.value;
    email2 = document.cadastro_cliente.email2.value;
        
    if(email2 != ""){
        
    	if(email != email2) {
            alert("E-mail não confere, por favor digite novamente");
            document.cadastro_cliente.email2.value = "";
        }
    } 
}

//Validar Email
function verificaEmail(email)
{
  if ((email.value.length != 0) && ((email.value.indexOf("@") < 1) ))
  {
    alert('Email incorreto!');
	document.email.focus();
  }
}


//Email Validado
function emailValidado() {
	
	email  = document.cadastro_cliente.email.value;
    email2 = document.cadastro_cliente.email2.value;
        
    if(email2 != ""){
        
    	if(email != email2) {
            alert("E-mail não confere, por favor digite novamente");
            document.cadastro_cliente.email2.value = "";
            document.cadastro_cliente.senha.value = "";
            document.cadastro_cliente.senha_confirmar.value = "";
            return false;
        }
    }
    return  true;
}

//###########################################################
//##													    ##
//##	    Autor: DM Tecnologia de Informacao  		    ##
//##													    ##
//##		    Valida campos da Data    				    ##
//##             										    ##
//## Usar: onclick="return habilitaCampo('id1','id2','id3') ##
//##													    ##
//###########################################################

function habilitaCampo(id1,id2,id3) {
	
	if((document.getElementById(id1).value != "") && (document.getElementById(id2).value != "") && (document.getElementById(id3).value != "")) 
		return true;
	else {
		alert("Preencha Data do Evento");
		return false;
	}		
}

//########################################################
//##													##
//##	    Autor: DM Tecnologia de Informacao  		##
//##													##
//##		    Coloca só Numeros no Input				##
//##													##
//##  Usar: onkeypress="return apenasNumeros(event);"   ##
//##													##
//########################################################


function apenasNumero(e) {
	
	var key;
	var keychar;
	var reg;

	if(window.event) {
	  // Para IE, e.keyCode ou window.event.keyCode pode ser usado
	  key = e.keyCode;
	} else if(e.which) {
	  // Netscape
	  key = e.which;
	} else {
	  // Se nao tiver evento, entao passa direto
	  return true;
	}
	if(key != 8){
		keychar = String.fromCharCode(key);
		reg = /\d/;
		// return !reg.test(keychar); ===> para tirar números é necessário tirar o exclamação (!)
		return reg.test(keychar);
	} else {
		return true;
	}
}

//########################################################
//##													##
//##	    Autor: DM Tecnologia de Informacao  		##
//##													##
//##		    Coloca só Letras no Input				##
//##													##
//##   Usar: onkeypress="return apenasLetras(event);"   ##
//##													##
//########################################################
function apenasLetras(e) {
	
	var key;
	var keychar;
	var reg;

	if(window.event) {
	  // Para IE, e.keyCode ou window.event.keyCode pode ser usado
	  key = e.keyCode;
	} else if(e.which) {
	  // Netscape
	  key = e.which;
	} else {
	  // Se nao tiver evento, entao passa direto
	  return true;
	}
	if(key != 8){
		keychar = String.fromCharCode(key);
		reg = /\d/;
		//return !reg.test(keychar); //===> para tirar numeros eh necessario tirar o exclamacao (!)
		return !reg.test(keychar);
	} else {
		return true;
	}
}

//########################################################
//##													##
//##	    Autor: DM Tecnologia de Informacao  		##
//##													##
//##		    Formatar Campo Monetario				##
//##													##
//##	Usar: onkeyup="formataValor(this.id,7,event)"	##
//##	Obs: Lembre de fazer o tratamento ao inserir	##
//##		 no banco de dados							##
//##													##
//########################################################
function formataValor(id,tammax,teclapres) {

	// Internet Explorer
	if(window.event) { 
		var tecla = teclapres.keyCode;
	} 
	// Nestcape / firefox
	else if(teclapres.which) {
		var tecla = teclapres.which;
	}

	vr = document.getElementById(id).value;
	vr = vr.toString().replace( "/", "" );
	vr = vr.toString().replace( "/", "" );
	vr = vr.toString().replace( ",", "" );
	vr = vr.toString().replace( ".", "" );
	vr = vr.toString().replace( ".", "" );
	vr = vr.toString().replace( ".", "" );
	vr = vr.toString().replace( ".", "" );
	tam = vr.length;
	
	if (tam < tammax && tecla != 8){
		tam = vr.length + 1; 
	}
	
	if (tecla == 8 ){ 
		tam = tam - 1; 
	}
	
	if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ){
		if ( tam <= 2 ){
			document.getElementById(id).value = vr; 
		}
		if ( (tam > 2) && (tam <= 5) ){
			document.getElementById(id).value = vr.substr( 0, tam - 2 ) + ',' + vr.substr( tam - 2, tam ); 
		}
		if ( (tam >= 6) && (tam <= 8) ){
			document.getElementById(id).value = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ); 
		}
		if ( (tam >= 9) && (tam <= 11) ){
			document.getElementById(id).value = vr.substr( 0, tam - 8 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ); 
		}
		if ( (tam >= 12) && (tam <= 14) ){
			document.getElementById(id).value = vr.substr( 0, tam - 11 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ); 
		}
		if ( (tam >= 15) && (tam <= 17) ){
			document.getElementById(id).value = vr.substr( 0, tam - 14 ) + '.' + vr.substr( tam - 14, 3 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam );
		}
	} 
}

//########################################################
//##													##
//##	Autor: DM Tecnologia de Informacao				##
//##													##
//##		Validação de campos gererica				##
//##													##
//##	Usar: onsubmit="return validaForm(this)"		##
//##	Obs: Dentro do <form></form>					##
//##													##
//########################################################
function validaForm(formulario) {
   var mensagem = '';
   var primeiro = 0;
   for (var i = 0; i < formulario.length; i++) {
       if (formulario.elements[i].getAttribute('erro')) {
          if ((formulario.elements[i].value == '') ||
             (formulario.elements[i].value.length == 0) ||
             (formulario.elements[i].selectedIndex <= 0)
             ) {
             mensagem = mensagem + formulario.elements[i].getAttribute('erro') + "\n";
             // troca a cor da borda do campo
             formulario.elements[i].style.border = '2px solid #f00';
             if (primeiro == 0) { var primeiro = i; }
          }
      }
   }
   if (mensagem != '') {
      formulario.elements[primeiro].focus();
      alert(mensagem);
      return false;
   } else {
       return true;
   }
} 


//########################################################
//##													##
//##	Autor: DM Tecnologia de Informacao				##
//##													##
//##				Ajax gererica						##
//##													##
//########################################################
function get(tI) { // Esta funcao pega o elemento pelo ID
  if (document.getElementById) { 
  	return document.getElementById(tI); 
  }
  else if (document.all) {
  	return document.all[tI]; 
  } else 
  	return false;
}

function ajax(valor,url,div,valor2,valor3,valor4){ 
	req = null; 
	if (window.XMLHttpRequest){ 
		req = new XMLHttpRequest(); 
		req.onreadystatechange = function() {
			if(req.readyState == 4){
				if (req.status == 200){
					get(div).innerHTML = "Carregando....";
					get(div).innerHTML = req.responseText;
				} else{ 
					alert("Houve um problema ao obter os dados:\n" + req.statusText);
				}
			}
		}
		req.open("GET", url+'?valor='+valor+'&valor2='+valor2+'&valor3='+valor3+'&valor4='+valor4, true); 
		req.send(null);
	} else if (window.ActiveXObject){ 
				req = new ActiveXObject("Microsoft.XMLHTTP"); 
				if (req){ 
					req.onreadystatechange = function() {
						if(req.readyState == 4){
							if (req.status == 200){
								get(div).innerHTML = "Carregando....";
								get(div).innerHTML = req.responseText;
							} else{ 
								alert("Houve um problema ao obter os dados:\n" + req.statusText);
							}
						}
					}
					req.open("GET", url+'?valor='+valor+'&valor2='+valor2+'&valor3='+valor3+'&valor4='+valor4, true); 
					req.send();
				}
		}
}


//########################################################
//##													##
//##	Autor: DM Tecnologia de Informacao				##
//##													##
//##			Checkar todos os Checkbox				##
//##													##
//##	Usar: onclick="checkbox();"						##
//##	Obs: Dentro do <input type="checkbox"></input>	##
//##													##
//########################################################
function checkbox() {

	// Pega todos os campos do formulário
    campos = document.form.elements;

	// Verifica se o checkbox "todos" esta checado
	if(document.form.todos.checked == true){
    for (x=0; x<campos.length; x++)
      if (campos[x].type == "checkbox") campos[x].checked = true;
	}
	// Se o checkbox "todos" não tiver checado
	else{
	for (x=0; x<campos.length; x++)
      if (campos[x].type == "checkbox") campos[x].checked = false;	
	}

}

//########################################################
//##													##
//##	Autor: DM Tecnologia de Informacao				##
//##													##
//##			Confirmação de Apagar					##
//##													##
//##	Usar: ?											##
//##	Obs: Dentro do <input type="checkbox"></input>	##
//##													##
//########################################################
function confirmacao() {
	var answer = confirm("Tem certeza que deseja apagar?")
	if (answer){
		return true;
	}
	else{
		return false;
	}
}

//################################################################
//##															##
//##	    Autor: DM Tecnologia de Informacao  				##
//##															##
//##		    Mascara de CPF e CNPJ							##
//##			   												##
//##  Usar: onkeyup="mascaraTexto(event,'99.999.999/9999-99')"  ##
//##		onkeyup="mascaraTexto(event,'999.999.999-99')"		##
//##															##
//################################################################
function mascaraTexto(evento, mascara){  
      
	var campo, valor, i, tam, caracter;  
      
    if (document.all) // Internet Explorer  
       campo = evento.srcElement;  
    else // Nestcape, Mozzila  
        campo= evento.target;  
          
    valor = campo.value;  
    tam = valor.length;  
      
    for(i=0;i<mascara.length;i++){  
       caracter = mascara.charAt(i);  
       if(caracter!="9")   
          if(i<tam & caracter!=valor.charAt(i))  
             campo.value = valor.substring(0,i) + caracter + valor.substring(i,tam);  
    }  
 } 
 
//########################################################
//##													##
//##	    Autor: DM Tecnologia de Informacao  		##
//##													##
//##		    Colocar Curso em outro campo			##
//##													##
//##  Usar: onkeyup="proximoCampo(tamanho,'id1','id2')"	##
//##													##
//########################################################
function proximoCampo(tamanho,id_atual,id_proximo){
	var tam = document.getElementById(id_atual).value.length;
	if (tam == tamanho){
		document.getElementById(id_proximo).focus();
    }
}

//########################################################
//##													##
//##	    Autor: DM Tecnologia de Informacao  		##
//##													##
//##		    Validação de CPF e CNPJ					##
//##													##
//##  Usar: onchange="ConfereCIC(this)"				    ##
//##													##
//########################################################
function DigitoCPFCNPJ(numCIC) {
	var numDois = numCIC.substring(numCIC.length-2, numCIC.length);
	var novoCIC = numCIC.substring(0, numCIC.length-2);
	
	switch (numCIC.length) {
 		case 11 :
  			numLim = 11;
  			break;
 		case 14 :
  			numLim = 9;
  			break;
 		default : return false;
	}
	
	var numSoma = 0;
	var Fator = 1;
	
	for (var i=novoCIC.length-1; i>=0 ; i--) {
 		Fator = Fator + 1;
 		if (Fator > numLim) {
  			Fator = 2;
 		}
 		numSoma = numSoma + (Fator * Number(novoCIC.substring(i, i+1)));
	}
	
	numSoma = numSoma/11;
	var numResto = Math.round( 11 * (numSoma - Math.floor(numSoma)));
   	if (numResto > 1) {
 		numResto = 11 - numResto;
   	} else {
 		numResto = 0;
   	}
   	
   //-- Primeiro digito calculado.  Fara parte do novo calculo.
   var numDigito = String(numResto);
   novoCIC = novoCIC.concat(numResto);
   //--
   numSoma = 0;
   Fator = 1;
   
   for (var i=novoCIC.length-1; i>=0 ; i--) {
   		Fator = Fator + 1;
 		if (Fator > numLim) {
  			Fator = 2;
 		}
 		numSoma = numSoma + (Fator * Number(novoCIC.substring(i, i+1)));
	}
	
	numSoma = numSoma/11;
	numResto = numResto = Math.round( 11 * (numSoma - Math.floor(numSoma)));
   	if (numResto > 1) {
 		numResto = 11 - numResto;
   	} else {
 		numResto = 0;
   	}
   	
	//-- Segundo digito calculado.
	numDigito = numDigito.concat(numResto);
	if (numDigito == numDois) {
 		return true;
	} else {
 		return false;
	}
}


//-- Retorna uma string apenas com os numeros da string enviada
function ApenasNum(strParm) {
	strParm = String(strParm);
	var chrPrt = "0";
	var strRet = "";
	var j=0;
	
	for (var i=0; i < strParm.length; i++) {
 		chrPrt = strParm.substring(i, i+1);
 		if ( chrPrt.match(/\d/) ) {
  			if (j==0) {
   				strRet = chrPrt;
   				j=1;
  			} else {
   				strRet = strRet.concat(chrPrt);
  			}
 		}
	}
	return strRet;
}

//-- Somente aceita os caracteres vï¿?lidos para CPF e CNPJ.
function PreencheCIC(objCIC) {
	var chrP = objCIC.value.substring(objCIC.value.length-1, objCIC.value.length);

	if ( !chrP.match(/[0-9]/) && !chrP.match(/[\/.-]/) ) {
 		objCIC.value = objCIC.value.substring(0, objCIC.value.length-1);
 		return false;
	}
	return true;
}

function FormataCIC (numCIC) {
	numCIC = String(numCIC);
	switch (numCIC.length){
		case 11 :
 			return numCIC.substring(0,3) + "." + numCIC.substring(3,6) + "." + numCIC.substring(6,9) + "-" + numCIC.substring(9,11);
		case 14 :
 			return numCIC.substring(0,2) + "." + numCIC.substring(2,5) + "." + numCIC.substring(5,8) + "/" + numCIC.substring(8,12) + "-" + numCIC.substring(12,14);
		default :
 			alert("Tamanho incorreto do CNPJ!");
 			return false;
	}
}

//-- Remove os sinais, deixando apenas os numeros e reconstroi o CPF ou CNPJ, verificando a validade
//-- Recebe como parametros o numero do CPF ou CNPJ, com ou sem sinais e o atualiza com sinais validado.
function ConfereCIC(objCIC,tipo) {
	if (objCIC.value == null) {
 		alert("Preenchimento obrigatório do "+tipo);
 		objCIC.value='';
 		objCIC.focus();
 		return false;
	}
	var strCPFPat  = /^\d{3}\.\d{3}\.\d{3}-\d{2}$/;
	var strCNPJPat = /^\d{2}\.\d{3}\.\d{3}\/\d{4}-\d{2}$/;
	numCPFCNPJ = ApenasNum(objCIC.value);

	if (!DigitoCPFCNPJ(numCPFCNPJ)) {
 		alert("Atenção: Dígito verificador do "+tipo+" é inválido!");
 		objCIC.value='';
 		objCIC.focus();
 		return false;
	}

	objCIC.value = FormataCIC(numCPFCNPJ);

	if (objCIC.value.match(strCNPJPat)) {
 		return true;
	}
	else if (objCIC.value.match(strCPFPat)) {
 		return true;
	} else {
 		alert("Digite um "+tipo+" válido!");
 		objCIC.value='';
 		objCIC.focus();
 		return false;
	}
}
