// essa função cria o objeto XMLHttp
// Exemplo:
// <a href="javascript: inner('arquivo.php','id_corpo');">link</a>
function Ajax() { 
	var XMLHttp; 
	try { 
		XMLHttp=new XMLHttpRequest(); 
	} 
	catch(ee) { 
		try {
			XMLHttp=new ActiveXObject("Msxml2.XMLHTTP"); 
		} catch(e) { 
		try {
			XMLHttp=new ActiveXObject("Microsoft.XMLHTTP"); } 
		catch(e) { 
			XMLHttp=false; 
			} 
		} 
	} 
	return XMLHttp; 
}
// função para não ficar fazeendo 'document.getElementByID('');
function pegaID(ID) { 
	return document.getElementById(ID); 
}

// Função que faz a requisicao assíncrona de um arquivo e retorna o seu HTML
function call(arquivo,ID,carregando) {
	var ajax_obj = new Ajax(); // cria a instancia da função Ajax()
	var area = pegaID(ID); // pega o ID passado
	ajax_obj.open('GET', arquivo, true); // fala o metodo para passar os dados para o arquivo
	ajax_obj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; iso-8859-1");
	ajax_obj.setRequestHeader("CharSet", "iso-8859-1")
	ajax_obj.setRequestHeader("Cache-Control", "no-cache");
	ajax_obj.setRequestHeader("Pragma", "no-cache");
	ajax_obj.onreadystatechange = function() {
	if(carregando == 1){ // coloca o texto 'Carregando' na area
		area.innerHTML = "<center><span style='background: #CC0000; color: white;'>Carregando...</span></center>"; 
	} 
	if (ajax_obj.readyState == 4) { // se objeto carregado 'readyState == 4'
		var retorno = ajax_obj.responseText; // recupera o HTML do arquivo
		//retorno = retorno.replace(/\+/g," \"); // naum sei o q faz ;-)
		retorno = unescape(retorno); // naum sei o q faz ;-)
		//alert(retorno);
		area.innerHTML = retorno; // insere o HTML na DIV especificada
	}
}
ajax_obj.send(null); // naum sei o q faz ;-)
}
// Esta serve para aplicar uma mascata em um campo qualquer.
// Ex em CPF: onkeyup= "mascara(this, '999.999.999-20', event);"
function mascara(objeto, sMask, evtKeyPress) {

      var i, nCount, sValue, fldLen, mskLen,bolMask, sCod, nTecla;

      if(document.all) { // Internet Explorer
        nTecla = evtKeyPress.keyCode; }
      else if(document.layers) { // Nestcape
        nTecla = evtKeyPress.which;
      }

      sValue = objeto.value;

      // Limpa todos os caracteres de formatação que
      // já estiverem no campo.
      sValue = sValue.toString().replace( "-", "" );
      sValue = sValue.toString().replace( "-", "" );
      sValue = sValue.toString().replace( ".", "" );
      sValue = sValue.toString().replace( ".", "" );
      sValue = sValue.toString().replace( "/", "" );
      sValue = sValue.toString().replace( "/", "" );
      sValue = sValue.toString().replace( ":", "" );
      sValue = sValue.toString().replace( ":", "" );
      sValue = sValue.toString().replace( "(", "" );
      sValue = sValue.toString().replace( "(", "" );
      sValue = sValue.toString().replace( ")", "" );
      sValue = sValue.toString().replace( ")", "" );
      sValue = sValue.toString().replace( " ", "" );
      sValue = sValue.toString().replace( " ", "" );
      fldLen = sValue.length;
      mskLen = sMask.length;

      i = 0;
      nCount = 0;
      sCod = "";
      mskLen = fldLen;

      while (i <= mskLen) {
        bolMask = ((sMask.charAt(i) == "-") || (sMask.charAt(i) == ".") || (sMask.charAt(i) == "/") || (sMask.charAt(i) == ":"))
        bolMask = bolMask || ((sMask.charAt(i) == "(") || (sMask.charAt(i) == ")") || (sMask.charAt(i) == " "))

        if (bolMask) {
          sCod += sMask.charAt(i);
          mskLen++; }
        else {
          sCod += sValue.charAt(nCount);
          nCount++;
        }

        i++;
      }

      objeto.value = sCod;

      if (nTecla != 8) { // backspace
        if (sMask.charAt(i-1) == "9") { // apenas números...
          return ((nTecla > 47) && (nTecla < 58)); } // números de 0 a 9
        else { // qualquer caracter...
          return true;
        } }
      else {
        return true;
      }
}

// abre uma popup
function abrejanela(mValor,mNome,mWidth,mHeight) {
	window.open (mValor,mNome,"marginwidth=0,marginheight=0,status=0,resizable=yes,width="+mWidth+",height="+mHeight+",left=0,top=0,scrollbars=yes");
}

//validação de todos os inputs do documento.
function valida_input(){
	var galera = document.getElementsByTagName('input');
	for(i = 0; i<=galera.length; i++){
		if(galera[i].value == ''){ 
			alert("Preencha todos os campos!");
			return false;
		}
	}
	return true;
}

// função para validar campos passados por uma string.
// sepadaos por virgula: 'nome,email'
function testa(string){
	//alert(string);
	var campos   = string.split(",");
	var erro     = 0;
	var mensagem = "Preencha todos os campos obrigatórios(*).";
	for(i = 0; i < campos.length; i++){
		if(document.getElementById(campos[i]).value == ""){
			//alert(document.getElementById(campos[i]).name);
			erro++;
		}
	}
	
	if(erro > 0){
		alert(mensagem);
		return false;
	}
	
	return true;
}

// redir = endereço para onde será redirecionado.
// frase = a frase que aparece-rá como pergunta.
function confirmaRedirect(redir,frase){
	if(confirm(frase)){
		location.href = redir;
	}
}

/*
 * Função serve para marcar/desmarcar 
 * todos os checkhox com um determinado
 * nome.
 *
 * todos: Nome do checkbox que quando clicado marca todos;
 * nome : Nome dos checkbox que serão marcados;  
 */
function marca(todos,nome){
	var ch = document.getElementsByTagName('input');
	for(i=0;i<=ch.length;i++){
		if(document.getElementById(todos).checked == true){
			var status = true;
		} else {
			var status = false;
		}
		if(ch[i].name == nome){ 
			ch[i].checked = status;
		}
	}
}

function acertacod(campo){
	var cod = document.getElementById(campo).value;
	var arr = cod.split('=');
	if(arr.length > 1){
		if(arr[1].length > 11){
			document.getElementById(campo).value = arr[1].substr(0,11);
		} else {
			document.getElementById(campo).value = arr[1];
		}
	}
}

function mostraPedido(pedido){
	status = document.getElementById(pedido).style.display;
	if(status == "none"){
		document.getElementById(pedido).style.display = "";
	} else {
		document.getElementById(pedido).style.display = "none";
	}
}

function mascara(objeto, sMask, evtKeyPress) {

      var i, nCount, sValue, fldLen, mskLen,bolMask, sCod, nTecla;

      if(document.all) { // Internet Explorer
          nTecla = evtKeyPress.keyCode; }
      else if(document.layers) { // Nestcape
          nTecla = evtKeyPress.which;
      }

      sValue = objeto.value;

      // Limpa todos os caracteres de formatação que
      // já estiverem no campo.
      sValue = sValue.toString().replace( "-", "" );
      sValue = sValue.toString().replace( "-", "" );
      sValue = sValue.toString().replace( ".", "" );
      sValue = sValue.toString().replace( ".", "" );
      sValue = sValue.toString().replace( "/", "" );
      sValue = sValue.toString().replace( "/", "" );
      sValue = sValue.toString().replace( ":", "" );
      sValue = sValue.toString().replace( ":", "" );
      sValue = sValue.toString().replace( "(", "" );
      sValue = sValue.toString().replace( "(", "" );
      sValue = sValue.toString().replace( ")", "" );
      sValue = sValue.toString().replace( ")", "" );
      sValue = sValue.toString().replace( " ", "" );
      sValue = sValue.toString().replace( " ", "" );
      fldLen = sValue.length;
      mskLen = sMask.length;

      i = 0;
      nCount = 0;
      sCod = "";
      mskLen = fldLen;

      while (i <= mskLen) {
        bolMask = ((sMask.charAt(i) == "-") || (sMask.charAt(i) == ".") || (sMask.charAt(i) == "/") || (sMask.charAt(i) == ":"))
        bolMask = bolMask || ((sMask.charAt(i) == "(") || (sMask.charAt(i) == ")") || (sMask.charAt(i) == " "))

        if (bolMask) {
            sCod += sMask.charAt(i);
            mskLen++; }
        else {
           sCod += sValue.charAt(nCount);
           nCount++;
        }

          i++;
      }

      objeto.value = sCod;

      if (nTecla != 8) { // backspace
        if (sMask.charAt(i-1) == "9") { // apenas números...
            return ((nTecla > 47) && (nTecla < 58)); } // números de 0 a 9
        else { // qualquer caracter...
            return true;
        } 
      } else {
          return true;
      }
}


function mascaraSoNumero(num, tammax){
     
    num.value = num.value.replace(/[^0-9]/gm, '');
    var d = '';
    var tam = 0;
    var a = 0;
    d = d + num.value;
    tam = d.length;
    a = d.substr(tam-1,1);
    if (isNaN(a) || a == ' '){
        num.value = d.substr(0,tam-1);
    }
    if (tammax && tam == tammax){
        num.value = d.substr(0,tam-1);
        return;
    }
}