
if (navigator.appName.indexOf('Microsoft') != -1){
	clientNavigator = "IE";
 }else{
	clientNavigator = "Other";
 }
 
function proxInputNF(teclaPress,proxInput){
	if(teclaPress.keyCode==13){	
		$get(proxInput).focus();	
	}
} 
function addFlash(movie, align, bgcolor, width, height){  
    var swf = 
      '<object '
    + 'classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" '
    + 'codebase="https://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,79,0" '
	+ 'width="'+ width +'" '
	+ 'height="'+ height +'"> '
    + '<param name="movie"  value="' + movie + '"/> '
    + '<param name="quality" value="high"/> '
	+ '<param name="scale" value="noscale"/> '
	+ '<param name="salign" value="' + align + '"/> '
	+ '<param name="bgcolor" value="' + bgcolor + '"/> '
	+ '<param name="menu" value="false"/> '
    + '<embed src="' + movie + '" '
    + 'bgcolor="' + bgcolor + '" '
	+ 'menu="false" '
	+ 'quality="high" '
	+ 'scale="noscale" '
	+ 'salign="' + align + '" '
	+ 'width="'+ width +'" '
	+ 'height="'+ height +'" '
	+ 'type="application/x-shockwave-flash" '
	+ 'other="foo" '
	+ 'pluginspage="https://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash"/> '
	+ '</object>'
	;
	document.write(swf);
}

function Bloqueia_Caracteres(evnt){
 //Função permite digitação de números
 	if (clientNavigator == "IE"){
		if (evnt.keyCode == 44)
			return true;
		else{ 
 			if (evnt.keyCode < 48 || evnt.keyCode > 57){
 				return false
 			}
		}
 	} else{
 		if ((evnt.charCode < 48 || evnt.charCode > 57) && evnt.keyCode == 0){
 			return false
 		}
 	}
	return true;
}
function Bloqueia_Car_Espciais(evnt){
 	if (clientNavigator == "IE"){
  		if ((evnt.keyCode < 40 || evnt.keyCode > 122) || (evnt.keyCode == 94 || evnt.keyCode == 96)){
		  if (evnt.keyCode == 32 || evnt.keyCode == 33 || evnt.keyCode == 13)
		    return true
		  else 
 			return false
 		}
 	}
}

function $get(idElemento){
	return document.getElementById(idElemento);
}

function EnviarPressEnter(tecla){
  if(tecla==13) 
    document.forms[0].submit();
}

function vai (url){
  location.replace(url);
}

function msgRetorno (msg,url){
  if (msg)
 	 alert(msg);		
  location.replace(url);
}

function number_format (number, decimals, dec_point, thousands_sep){
  var exponent = "";
  var numberstr = number.toString ();
  var eindex = numberstr.indexOf ("e");
  if (eindex > -1)
  {
    exponent = numberstr.substring (eindex);
    number = parseFloat (numberstr.substring (0, eindex));
  }
  
  if (decimals != null)
  {
    var temp = Math.pow (10, decimals);
    number = Math.round (number * temp) / temp;
  }
  var sign = number < 0 ? "-" : "";
  var integer = (number > 0 ? 
      Math.floor (number) : Math.abs (Math.ceil (number))).toString ();
  
  var fractional = number.toString ().substring (integer.length + sign.length);
  dec_point = dec_point != null ? dec_point : ".";
  fractional = decimals != null && decimals > 0 || fractional.length > 1 ? 
               (dec_point + fractional.substring (1)) : "";
  if (decimals != null && decimals > 0)
  {
    for (i = fractional.length - 1, z = decimals; i < z; ++i)
      fractional += "0";
  }
  
  thousands_sep = (thousands_sep != dec_point || fractional.length == 0) ? 
                  thousands_sep : null;
  if (thousands_sep != null && thousands_sep != "")
  {
	for (i = integer.length - 3; i > 0; i -= 3)
      integer = integer.substring (0 , i) + thousands_sep + integer.substring (i);
  }
  
  return sign + integer + fractional + exponent;
}

// JavaScript Document
/////////////////////////////////////////////////////////////////////////////////////////////////////
function validaData(str,nome_campo) {
	
	dia = (str.substring(0,2)); 
    mes = (str.substring(3,5)); 
	ano = (str.substring(6,10)); 

	cons = true; 
		
	// verifica se foram digitados números
	if (isNaN(dia) || isNaN(mes) || isNaN(ano)){
		alert("Preencha a data somente com números."); 
		document.getElementById(nome_campo).value = "";
		document.getElementById(nome_campo).focus(); 
		return false;
	}
		
    // verifica o dia valido para cada mes 
    if ((dia < 01) ||(dia < 01 || dia > 30) && 
		(mes == 04 || mes == 06 || 
		 mes == 09 || mes == 11 ) || 
		 dia > 31) { 
    	cons = false; 
	} 
	// verifica se o mes e valido 
	if (mes < 01 || mes > 12 ) { 
		cons = false; 
	} 

	// verifica se e ano bissexto 
	if (mes == 2 && ( dia < 01 || dia > 29 || 
	   ( dia > 28 && 
	   (parseInt(ano / 4) != ano / 4)))) { 
		cons = false; 
	} 

	if (cons == false) { 
		alert("A data inserida não é válida: " + str); 
		cons = false;
	} 

	// Verifico se o ano possui 4 digitos 
	if (ano.length < 4){ 
		alert("A data inserida não é válida: " + str +"\nObs: O ano deve possuir 4 digitos"); 
    	cons = false;
	}
	return cons;
}

// colocar no evento onKeyUp passando o objeto como parametro
function formata_data(val){
   	var pass = val.value;
	var expr = /[0123456789]/;
		
	for(i=0; i<pass.length; i++){
		// charAt -> retorna o caractere posicionado no índice especificado
		var lchar = val.value.charAt(i);
		var nchar = val.value.charAt(i+1);
	
		if(i==0){
		   // search -> retorna um valor inteiro, indicando a posição do inicio da primeira
		   // ocorrência de expReg dentro de instStr. Se nenhuma ocorrencia for encontrada o método retornara -1
		   // instStr.search(expReg);
		   if ((lchar.search(expr) != 0) || (lchar>3)){
			  val.value = "";
		   }
		   
		}else if(i==1){
			   
			   if(lchar.search(expr) != 0){
				  // substring(indice1,indice2)
				  // indice1, indice2 -> será usado para delimitar a string
				  var tst1 = val.value.substring(0,(i));
				  val.value = tst1;				
 				  continue;			
			   }
			   
			   if ((nchar != '/') && (nchar != '')){
				 	var tst1 = val.value.substring(0, (i)+1);
				
					if(nchar.search(expr) != 0) 
						var tst2 = val.value.substring(i+2, pass.length);
					else
						var tst2 = val.value.substring(i+1, pass.length);
	
					val.value = tst1 + '/' + tst2;
			   }

		 }else if(i==4){
			
				if(lchar.search(expr) != 0){
					var tst1 = val.value.substring(0, (i));
					val.value = tst1;
					continue;			
				}
		
				if	((nchar != '/') && (nchar != '')){
					var tst1 = val.value.substring(0, (i)+1);

					if(nchar.search(expr) != 0) 
						var tst2 = val.value.substring(i+2, pass.length);
					else
						var tst2 = val.value.substring(i+1, pass.length);
	
					val.value = tst1 + '/' + tst2;
				}
   		  }
		
		  if(i>=6){
			  if(lchar.search(expr) != 0) {
					var tst1 = val.value.substring(0, (i));
					val.value = tst1;			
			  }
		  }
	 }
	
     if(pass.length>10)
		val.value = val.value.substring(0, 10);
	 	return true;
}

// Retira caracteres invalidos da string
function Limpar(valor, validos){
	
	var result = "";
	var aux;
	for (var i=0; i < valor.length; i++){
		aux = validos.indexOf(valor.substring(i, i+1));
		if(aux>=0){
		 result += aux;
		}
	}
	return result;
}

//Formata número tipo moeda usando o evento onKeyDown
function Formata(campo,tammax,teclapres,decimal){
   var tecla = teclapres.keyCode;
   vr = Limpar(campo.value,"0123456789");
   tam = vr.length;
   dec = decimal;
   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 <= dec ){
         campo.value = vr ;
      }
      if((tam > dec) && (tam <= 5)){
         campo.value = vr.substr( 0, tam - 2 ) + "," + vr.substr( tam - dec, tam ) ;
      }
      if((tam >= 6) && (tam <= 8)){
         campo.value = vr.substr( 0, tam - 5 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ;
      }
      if((tam >= 9) && (tam <= 11)){
         campo.value = vr.substr( 0, tam - 8 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ;
      }
      if((tam >= 12) && (tam <= 14)){
         campo.value = vr.substr( 0, tam - 11 ) + "." + vr.substr( tam - 11, 3 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ;
      }
      if((tam >= 15) && (tam <= 17)){
         campo.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 ) ;
      }
   }
}



// Funcao CheckBox 
function selecionar() {
    var campo = document.forms[0].elements['campo'];
	var varChecked =  document.forms[0].elements['todos'].checked;

	var selecionado;
	if (!varChecked) 
		uncheckAll(campo);
	else
		checkAll(campo);
}

// Seleciona todos os checkbox
function checkAll(field) {
	for (i = 0; i < field.length; i++) {
		field[i].checked = true;
	}
}
// Deseleciona todos os checkbox
function uncheckAll(field) {
	for (i = 0; i < field.length; i++) {
		field[i].checked = false;
	}
}

function checkEmail(email){
   if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)) || !email) 
     return false;
   else 
     return true;
}

function imprimir(){
  window.parent.focus();
  window.parent.print();
}

function Ajusta_Hora(input, evnt){
//Ajusta máscara de Hora e só permite digitação de números
 	if (input.value.length == 2){
 		if(clientNavigator == "IE"){
 			input.value += ":";
 		}else{
 			if(evnt.keyCode == 0){
 				input.value += ":";
 			}
 		}
 	}
 //Chama a função Bloqueia_Caracteres para só permitir a digitação de números
 	return Bloqueia_Caracteres(evnt);
 }

 function Ajusta_Cep(input, evnt){
 //Ajusta máscara de CEP e só permite digitação de números
 	if (input.value.length == 5){
 		if(clientNavigator == "IE"){
 			input.value += "-";
 		}else{
 			if(evnt.keyCode == 0){
 				input.value += "-";
 			}
 		}
 	}
 //Chama a função Bloqueia_Caracteres para só permitir a digitação de números
 	return Bloqueia_Caracteres(evnt);
 }



function FormataCNPJ(Campo, teclapres){

   var tecla = teclapres.keyCode;
   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);
      }
 //Chama a função Bloqueia_Caracteres para só permitir a digitação de números
	return Bloqueia_Caracteres(teclapres);  
}

function Mascara(objeto, evt, mask) {
 
	var LetrasU = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
	var LetrasL = 'abcdefghijklmnopqrstuvwxyz';
	var Letras  = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
	var Numeros = '0123456789';
	var Fixos  = '().-:/ '; 
	var Charset = " !\"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_/`abcdefghijklmnopqrstuvwxyz{|}~";
	
	evt = (evt) ? evt : (window.event) ? window.event : "";
	var value = objeto.value;
	if (evt) {
	 var ntecla = (evt.which) ? evt.which : evt.keyCode;
	 tecla = Charset.substr(ntecla - 32, 1);
	 if (ntecla < 32) return true;
	
	 var tamanho = value.length;
	 if (tamanho >= mask.length) return false;
	
	 var pos = mask.substr(tamanho,1); 
	 while (Fixos.indexOf(pos) != -1) {
	  value += pos;
	  tamanho = value.length;
	  if (tamanho >= mask.length) return false;
	  pos = mask.substr(tamanho,1);
	 }
	
	 switch (pos) {
	   case '#' : if (Numeros.indexOf(tecla) == -1) return false; break;
	   case 'A' : if (LetrasU.indexOf(tecla) == -1) return false; break;
	   case 'a' : if (LetrasL.indexOf(tecla) == -1) return false; break;
	   case 'Z' : if (Letras.indexOf(tecla) == -1) return false; break;
	   case '*' : objeto.value = value; return true; break;
	   default : return false; break;
	 }
	}
	objeto.value = value; 
	return true;
}

function MaskTelefone(objeto, evt) { 
  return Mascara(objeto, evt, '(##) ####-####');
}

function MaskCPF(objeto, evt) { 
  return Mascara(objeto, evt, '###.###.###-##');
}

function janelaCenter(url, nome, parms, width, height) {
 	var str = "height=" + height + ",innerHeight=" + height;
	str += ",width=" + width + ",innerWidth=" + width;
	if (parms != "") {
		str += ", " + parms;
	}
	if (window.screen) {
		var ah = screen.availHeight - 30;
		var aw = screen.availWidth - 10;
		var xc = (aw - width) / 2;
		var yc = (ah - height) / 2;

	} else {
		var xc = 0, xy = 0;
	}
	str += ",left=" + xc + ",screenX=" + xc;
	str += ",top=" + yc + ",screenY=" + yc;
	hwnd = window.open(url, nome, str);
	if(hwnd.window.focus){hwnd.window.focus();}
//	if(text != "") hwnd.document.write(text);
//	hwnd.document.close();
	return hwnd;
}

// Retorno o valor selecionado do Radio Button 
function valRadio(nomeCampo){ 
  var i;
  for (i=0; i < nomeCampo.length; i++){ 
    if (nomeCampo[i].checked) 
      return nomeCampo[i].value; 
  } 	
}

function valida_camposArray(campo,nome){
  var d = document;
  for (var i = 0;i<campo.length; i++){
    var vlrCampo = d.getElementById(campo[i]).value; 
    if (vlrCampo == ""  || vlrCampo == 0){
		alert ("Campo "+nome[i]+" esta em branco!");
		d.getElementById(campo[i]).focus();
		return false;
    }
	if (campo[i] == "email") {
		if (checkEmail(vlrCampo) == false){
			alert ("Campo E-mail esta em inválido!");
			d.getElementById(campo[i]).focus();
			return false;
		}
  	}
  }
  return true;
}

// Fechar Janela 
function fechaJanela(){
	top.window.close();
}

/*funcao para redirecionar*/
function MM_jumpMenu(targ,selObj,restore){
  eval("window.location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}

function voltar(){
   history.back();
}

function cancelar(){
   document.forms[0].reset();
}

function fechaJanela(){
  top.window.close();
}

// Codificar Strings

function url_encode(str) {  
        var hex_chars = "0123456789ABCDEF";  
        var noEncode = /^([a-zA-Z0-9\_\-\.])$/;  
        var n, strCode, hex1, hex2, strEncode = "";  

        for(n = 0; n < str.length; n++) {  
            if (noEncode.test(str.charAt(n))) {  
                strEncode += str.charAt(n);  
            } else {  
                strCode = str.charCodeAt(n);  
                hex1 = hex_chars.charAt(Math.floor(strCode / 16));  
                hex2 = hex_chars.charAt(strCode % 16);  
                strEncode += "%" + (hex1 + hex2);  
            }  
        }  
	return strEncode;  
}  

// Descodificar String 

function url_decode(str) {  
	var n, strCode, strDecode = "";  

	for (n = 0; n < str.length; n++) {  
		if (str.charAt(n) == "%") {  
			strCode = str.charAt(n + 1) + str.charAt(n + 2);  
			strDecode += String.fromCharCode(parseInt(strCode, 16));  
			n += 2;  
		} else {  
			strDecode += str.charAt(n);  
		}  
	}  

	return strDecode;  
} 

function saltaCampo(prox,teclapres){
    var tecla = teclapres.keyCode ? teclapres.keyCode : teclapres.which ? teclapres.which : teclapres.charCode;
	if (tecla == 13){
	  document.getElementById(prox).select(); //se não quiser o foco, desabilite!
	  document.getElementById(prox).focus();
	}
}

// Captura o valor selecionado no Radion Button 
function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

var reTime1 = /^\d{2}:\d{2}$/; //Horário HH:MM simple
var reTime2 = /^([0-1]\d|2[0-3]):[0-5]\d$/; //Horário HH:MM 24h
var reTime3 = /^(0[1-9]|1[0-2]):[0-5]\d$/; //Horário HH:MM 12h
var reTime4 = /^\d+:[0-5]\d:[0-5]\d$/;  //Tempo horas:MM:SS
var reTime5 = /^\d+:[0-5]\d:[0-5]\.\d{3}\d$/; //Tempo horas:MM:SS.mili

function validaHora(campo,pStr, pFmt){
	eval("reTime = reTime" + pFmt);
	if (!reTime.test(pStr)) {
		$("#"+campo).focus();
		alert(pStr + " NÃO é um horário válido.");
		return 1;
	} else {
		return 0;	
	}
} 

function IsNumeric(strString){
   var strValidChars = "0123456789.-";
   var strChar;
   var blnResult = true;

   if (strString.length == 0) return false;

   //  test strString consists of valid characters listed above
   for (i = 0; i < strString.length && blnResult == true; i++)
      {
      strChar = strString.charAt(i);
      if (strValidChars.indexOf(strChar) == -1)
         {
         blnResult = false;
         }
      }
   return blnResult;
}

/////////////Valores em dinheiro


function isNull(x){
    if((x == 'undefined') || (x == null)){return true;}
    else{return false;}
}

function abreM(pagina){
  hh = screen.availHeight - 65;
  ww = screen.availWidth - 10;
  window.open(pagina,'','top=0,left=0,width='+ww+',height='+hh+',status=yes');
  window.opener = self;
	
}
function changeColor(campo, classe) { 
	element = document.getElementById(campo.id); 
	event.cancelBubble = true; 
	element.className = classe;
} 