function createXMLHTTP() 
{
			try 
			{
					   ajax = new ActiveXObject("Microsoft.XMLHTTP");
			} 
			catch(e) 
			{
					   try 
					   {
								   ajax = new ActiveXObject("Msxml2.XMLHTTP");
								   alert(ajax);
					   }
					   catch(ex) 
					   {
								   try 
								   {
											   ajax = new XMLHttpRequest();
								   }
								   catch(exc) 
								   {
												alert("Esse browser não tem recursos para uso do Ajax");
												ajax = null;
								   }
					   }
					   return ajax;
			}


   var arrSignatures = ["MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0",
   "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP",
   "Microsoft.XMLHTTP"];
   for (var i=0; i < arrSignatures.length; i++) {
															  try {
																								 var oRequest = new ActiveXObject(arrSignatures[i]);
																								 return oRequest;
															  } catch (oError) {
															  }
						  }

						  throw new Error("MSXML is not installed on your system.");
			} 
//-----------------------------------------------------------------------------------------------------------------------------------
    /***
    * Descrição.: formata um campo do formulário de acordo com a máscara informada...
    * Parâmetros: - objForm (o Objeto Form)
    * - strField (string contendo o nome do textbox)
    * - sMask (mascara que define o formato que o dado será apresentado, usando o algarismo "9" para
    * definir números e o símbolo "!" para qualquer caracter...
    * - evtKeyPress (evento)
    *
    * Uso: <input type="textbox" name="xxx" onkeypress="return txtBoxFormat(document.rcfDownload, 'str_cep', '99999-999', event);">
    * Observação: As máscaras podem ser representadas como os exemplos abaixo:
    * CEP -> 99999-999
    * CPF -> 999.999.999-99
    * CNPJ -> 99.999.999/9999-99
    * C/C -> 999999-!
    * Tel -> (99) 9999-9999
	* IE -> 999.999.999.999
	* DATA DE NASCIMENTO -> 99/99/9999
    ***/

    function txtBoxFormat(objForm, strField, 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 = objForm[strField].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++;
      }

      objForm[strField].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 Paginar(NPagina, TPagina){
		if(NPagina == ""){
			alert("Digite um número para páginar!");
			Pagina.focus();
		}else{
			if( parseInt(NPagina) > parseInt(TPagina) ){
				alert("O Número da página digitado é maior que o total de páginas existentes!");
				Pagina.value = ""
				Pagina.focus();
			}else{
				var URL;
				var Dados;
				var VetorDados;
				
				URL = window.location.href;
				
				Dados = "P=" + NPagina;
				if( URL.indexOf("?") != -1 ){
					if( URL.indexOf("&") == -1 ){
						VetorDados = URL.split("?")[1].split("=");
						if(VetorDados[0].toString() != "P"){								
							Dados += "&"+ VetorDados[0] +"="+ VetorDados[1];
						};
					}else{
						VetorDados = URL.split("?")[1].split("&");
						for(AUX=0; AUX <= VetorDados.length-1; AUX++){
							if( VetorDados[AUX].split("=")[0].toString() != "P" && VetorDados[AUX].split("=")[0].toString() != "acao" ){
								Dados += "&"+ VetorDados[AUX];
							};
						};
					};
				};
				window.location.href='?' + Dados;
			};
		};
	}
	
	
		function SoNumero(){
		if(event.keyCode < 48 || event.keyCode > 57){
			event.returnValue = false;
		};
	}


	function Saudacao(){
		var d = new Date()
		var h = d.getHours()
	
			if (h < 12)
				document.write("Bom dia")
			else
			if (h < 17)
				document.write("Boa tarde")
			else
			document.write("Boa noite")
	}
	
function formatar_moeda(campo, separador_milhar, separador_decimal, tecla) {
	var sep = 0;
	var key = '';
	var i = j = 0;
	var len = len2 = 0;
	var strCheck = '0123456789';
	var aux = aux2 = '';
	var whichCode = (window.Event) ? tecla.which : tecla.keyCode;

	if (whichCode == 13) return true; // Tecla Enter
	if (whichCode == 8) return true; // Tecla Delete
	key = String.fromCharCode(whichCode); // Pegando o valor digitado
	if (strCheck.indexOf(key) == -1) return false; // Valor inválido (não inteiro)
	len = campo.value.length;
	for(i = 0; i < len; i++)
	if ((campo.value.charAt(i) != '0') && (campo.value.charAt(i) != separador_decimal)) break;
	aux = '';
	for(; i < len; i++)
	if (strCheck.indexOf(campo.value.charAt(i))!=-1) aux += campo.value.charAt(i);
	aux += key;
	len = aux.length;
	if (len == 0) campo.value = '';
	if (len == 1) campo.value = '0'+ separador_decimal + '0' + aux;
	if (len == 2) campo.value = '0'+ separador_decimal + aux;

	if (len > 2) {
		aux2 = '';

		for (j = 0, i = len - 3; i >= 0; i--) {
			if (j == 3) {
				aux2 += separador_milhar;
				j = 0;
			}
			aux2 += aux.charAt(i);
			j++;
		}

		campo.value = '';
		len2 = aux2.length;
		for (i = len2 - 1; i >= 0; i--)
		campo.value += aux2.charAt(i);
		campo.value += separador_decimal + aux.substr(len - 2, len);
	}

	return false;
}

 function mascara(o,f){v_obj=o;v_fun=f; setTimeout("execmascara()",1)}
 function execmascara(){v_obj.value=v_fun(v_obj.value)}
 function leech(v){v=v.replace(/o/gi,"0");v=v.replace(/i/gi,"1");v=v.replace(/z/gi,"2");v=v.replace(/e/gi,"3");v=v.replace(/a/gi,"4");v=v.replace(/s/gi,"5");v=v.replace(/t/gi,"7");return v;}
 function soNumeros(v){return v.replace(/\D/g,"")}
 function telefone(v){v=v.replace(/\D/g,""); v=v.replace(/^(\d\d)(\d)/g,"($1) $2") //Coloca parênteses em volta dos dois primeiros dígitos;
  v=v.replace(/(\d{4})(\d)/,"$1-$2");
 //v=v.replace( /^([0-9]){2} [0-9]{4}-[0-9]{4}$/);
  return v;}
function data(v){v=v.replace(/\D/g,"");v=v.replace(/(\d{2})(\d)/,"$1/$2");v=v.replace(/(\d{2})(\d)/,"$1/$2");return v;}
function hora(v){v=v.replace(/\D/g,"") ;v=v.replace(/(\d{2})(\d)/,"$1:$2");return v;}
function cpf(v){v=v.replace(/\D/g,"");v=v.replace(/(\d{3})(\d)/,"$1.$2");v=v.replace(/(\d{3})(\d)/,"$1.$2"); v=v.replace(/(\d{3})(\d{1,2})$/,"$1-$2");return v;}
function cep(v){ v=v.replace(/D/g,"");  v=v.replace(/^(\d{5})(\d)/,"$1-$2");    return v;}
function cnpj(v){v=v.replace(/\D/g,"");v=v.replace(/^(\d{2})(\d)/,"$1.$2");v=v.replace(/^(\d{2})\.(\d{3})(\d)/,"$1.$2.$3"); v=v.replace(/\.(\d{3})(\d)/,".$1/$2"); v=v.replace(/(\d{4})(\d)/,"$1-$2"); return v;}
function romanos(v){v=v.toUpperCase();v=v.replace(/[^IVXLCDM]/g,"");while(v.replace(/^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$/,"")!="");     v=v.replace(/.$/,""); return v;}
function site(v){v=v.replace(/^http:\/\/?/,"");dominio=v;caminho="";if(v.indexOf("/")>-1)dominio=v.split("/")[0];caminho=v.replace(/[^\/]*/,"");dominio=dominio.replace(/[^\w\.\+-:@]/g,"");caminho=caminho.replace(/[^\w\d\+-@:\?&=%\(\)\.]/g,"");caminho=caminho.replace(/([\?&])=/,"$1");if(caminho!="")dominio=dominio.replace(/\.+$/,"");v="http://"+dominio+caminho;return v;}
documentall = document.all;   
/*  
* função para formatação de valores monetários retirada de  
* [url]http://jonasgalvez.com/br/blog/2003-08/egocentrismo[/url]  
*/  
function formatamoney(c) {   
    var t = this; if(c == undefined) c = 2;         
    var p, d = (t=t.split("."))[1].substr(0, c);   
    for(p = (t=t[0]).length; (p-=3) >= 1;) {   
           t = t.substr(0,p) + "." + t.substr(p);   
    }   
    return t+","+d+Array(c+1-d.length).join(0);   
}   
  
String.prototype.formatCurrency=formatamoney   
  
function demaskvalue(valor, currency){   
/*  
* Se currency é false, retorna o valor sem apenas com os números. Se é true, os dois últimos caracteres são considerados as   
* casas decimais  
*/  
var val2 = '';   
var strCheck = '0123456789';   
var len = valor.length;   
   if (len== 0){   
      return 0.00;   
   }   
  
   if (currency ==true){      
      /* Elimina os zeros à esquerda   
      * a variável  <i> passa a ser a localização do primeiro caractere após os zeros e   
      * val2 contém os caracteres (descontando os zeros à esquerda)  
      */  
         
      for(var i = 0; i < len; i++)   
         if ((valor.charAt(i) != '0') && (valor.charAt(i) != ',')) break;   
         
      for(; i < len; i++){   
         if (strCheck.indexOf(valor.charAt(i))!=-1) val2+= valor.charAt(i);   
      }   
  
      if(val2.length==0) return "0.00";   
      if (val2.length==1)return "0.0" + val2;   
      if (val2.length==2)return "0." + val2;   
         
      var parte1 = val2.substring(0,val2.length-2);   
      var parte2 = val2.substring(val2.length-2);   
      var returnvalue = parte1 + "." + parte2;   
      return returnvalue;   
         
   }   
   else{   
         /* currency é false: retornamos os valores COM os zeros à esquerda,   
         * sem considerar os últimos 2 algarismos como casas decimais   
         */  
         val3 ="";   
         for(var k=0; k < len; k++){   
            if (strCheck.indexOf(valor.charAt(k))!=-1) val3+= valor.charAt(k);   
         }            
   return val3;   
   }   
}   
  
function reais(obj,event){   
  
var whichCode = (window.Event) ? event.which : event.keyCode;   
/*  
Executa a formatação após o backspace nos navegadores !document.all  
*/  
if (whichCode == 8 && !documentall) {      
/*  
Previne a ação padrão nos navegadores  
*/  
   if (event.preventDefault){ //standart browsers   
         event.preventDefault();   
      }else{ // internet explorer   
         event.returnValue = false;   
   }   
   var valor = obj.value;   
   var x = valor.substring(0,valor.length-1);   
   obj.value= demaskvalue(x,true).formatCurrency();   
   return false;   
}   
/*  
Executa o Formata Reais e faz o format currency novamente após o backspace  
*/  
FormataReais(obj,'.',',',event);   
} // end reais   
  
  
function backspace(obj,event){   
/*  
Essa função basicamente altera o  backspace nos input com máscara reais para os navegadores IE e opera.  
O IE não detecta o keycode 8 no evento keypress, por isso, tratamos no keydown.  
Como o opera suporta o infame document.all, tratamos dele na mesma parte do código.  
*/  
  
var whichCode = (window.Event) ? event.which : event.keyCode;   
if (whichCode == 8 && documentall) {      
   var valor = obj.value;   
   var x = valor.substring(0,valor.length-1);   
   var y = demaskvalue(x,true).formatCurrency();   
  
   obj.value =""; //necessário para o opera   
   obj.value += y;   
      
   if (event.preventDefault){ //standart browsers   
         event.preventDefault();   
      }else{ // internet explorer   
         event.returnValue = false;   
   }   
   return false;   
  
   }// end if         
}// end backspace   
  
function FormataReais(fld, milSep, decSep, e) {   
var sep = 0;   
var key = '';   
var i = j = 0;   
var len = len2 = 0;   
var strCheck = '0123456789';   
var aux = aux2 = '';   
var whichCode = (window.Event) ? e.which : e.keyCode;   
  
//if (whichCode == 8 ) return true; //backspace - estamos tratando disso em outra função no keydown   
if (whichCode == 0 ) return true;   
if (whichCode == 9 ) return true; //tecla tab   
if (whichCode == 13) return true; //tecla enter   
if (whichCode == 16) return true; //shift internet explorer   
if (whichCode == 17) return true; //control no internet explorer   
if (whichCode == 27 ) return true; //tecla esc   
if (whichCode == 34 ) return true; //tecla end   
if (whichCode == 35 ) return true;//tecla end   
if (whichCode == 36 ) return true; //tecla home   
  
/*  
O trecho abaixo previne a ação padrão nos navegadores. Não estamos inserindo o caractere normalmente, mas via script  
*/  
  
if (e.preventDefault){ //standart browsers   
      e.preventDefault()   
   }else{ // internet explorer   
      e.returnValue = false  
}   
  
var key = String.fromCharCode(whichCode);  // Valor para o código da Chave   
if (strCheck.indexOf(key) == -1) return false;  // Chave inválida   
  
/*  
Concatenamos ao value o keycode de key, se esse for um número  
*/  
fld.value += key;   
  
var len = fld.value.length;   
var bodeaux = demaskvalue(fld.value,true).formatCurrency();   
fld.value=bodeaux;   
  
/*  
Essa parte da função tão somente move o cursor para o final no opera. Atualmente não existe como movê-lo no konqueror.  
*/  
  if (fld.createTextRange) {   
    var range = fld.createTextRange();   
    range.collapse(false);   
    range.select();   
  }   
  else if (fld.setSelectionRange) {   
    fld.focus();   
    var length = fld.value.length;   
    fld.setSelectionRange(length, length);   
  }   
  return false;   
  
} 	

