function Bloqueia_Caracteres(evnt){
 //Função permite digitação de números
 	if (clientNavigator == "IE"){
 		if (evnt.keyCode < 48 || evnt.keyCode > 57){
 			return false
 		}
 	}else{
 		if ((evnt.charCode < 48 || evnt.charCode > 57) && evnt.keyCode == 0){
 			return false
 		}
 	}
}


// 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; 
  } 	
}

var isNN = (navigator.appName.indexOf("Netscape")!=-1);
function autoTab(input,len, e) {
    var keyCode = (isNN) ? e.which : e.keyCode; 
    var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];
    if(input.value.length >= len && !containsElement(filter,keyCode)) {
        input.value = input.value.slice(0, len);
        input.form[(getIndex(input)+1) % input.form.length].focus();
}

function containsElement(arr, ele) {
    var found = false, index = 0;
    while(!found && index < arr.length)
        if(arr[index] == ele)
            found = true;
        else
            index++;
        return found;
    }

function getIndex(input) {
    var index = -1, i = 0, found = false;
    while (i < input.form.length && index == -1)
        if (input.form[i] == input)index = i;
        else i++;
        return index;
    }
return true;
}
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;
}



function abrirImagem_test(foto,nome,parms,width, height) {
	Popup = janelaCenter(foto, nome, parms, width, height);
	Popup.document.open();
	Popup.document.write("<html><head><title>");
	Popup.document.write("Imagem");
	Popup.document.write("</title>");
	Popup.document.write('<script language=' + '\"JavaScript\">');
	Popup.document.write('function ' + 'resize() {');
	Popup.document.write('var x = ' + 'document.images[0].width;');
	Popup.document.write('var y = ' + 'document.images[0].height;');
	Popup.document.write('this.resizeTo ' + '(('+width+' + 10), ('+height+'+ 29));');
	Popup.document.write('}');
	Popup.document.write('</script>');
	Popup.document.write("</head><body leftmargin=0 topmargin=0 onload=\"resize()\">");
	Popup.document.write('<center>');
	Popup.document.write('<img src=\"' + foto + '\">');
	Popup.document.write("</center>");
	Popup.document.write("</body></html>");
	//Popup.document.close();
}



function abrirImagem(foto,nome,parms,width, height) {
	Popup = janelaCenter(foto, nome, parms, width, height);
	Popup.document.open();
	Popup.document.write("<html><head><title>");
	Popup.document.write("Imagem");
	Popup.document.write("</title>");
	Popup.document.write('<script language=' + '\"JavaScript\">');
	Popup.document.write('function ' + 'resize() {');
	Popup.document.write('var x = ' + 'document.images[0].width;');
	Popup.document.write('var y = ' + 'document.images[0].height;');
	Popup.document.write('this.resizeTo ' + '(('+width+' + 10), ('+height+'+ 29));');
	Popup.document.write('}');
	Popup.document.write('</script>');	
/*	Popup.document.write("<script>function botaodireito() {if (event.button==2) {alert('Copia não autorizada!!!')}}document.onmousedown=botaodireito</script>");*/

	Popup.document.write("</head><body onload=setInterval('window.clipboardData.clearData()',20) leftmargin=0 topmargin=0 onload='resize()' >");
	Popup.document.write('<center>');
	Popup.document.write('<img src=\"' + foto + '\">');
	Popup.document.write("</center>");
	Popup.document.write("</body></html>");
	//Popup.document.close();
}


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 clearCache(){
  try{ 
    var agt=navigator.userAgent.toLowerCase(); 
    if (agt.indexOf("msie") != -1) { 
    // IE clear HTTP Authentication 
    document.execCommand("ClearAuthenticationCache"); 
  } 
  else { 

    // Let's create an xmlhttp object 
    var xmlhttp = createXMLObject(); 
    // Let's get the force page to logout for mozilla 
    xmlhttp.open("GET",".force_logout_offer_login_mozilla",true,"logout","logout"); 
    // Let's send the request to the server 
    xmlhttp.send(""); 
    // Let's abort the request 
    xmlhttp.abort(); 
  } 
  // Let's redirect the user to the main webpage 
  window.location = "/rest/"; 
  } catch(e) { 
  // There was an error 
  alert("Erro"); 
  } 
}

function createXMLObject() { 
    try { 
        if (window.XMLHttpRequest) { 
            xmlhttp = new XMLHttpRequest(); 
        } 
        // code for IE 
        else if (window.ActiveXObject) { 
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
        } 
    } catch (e) { 
        xmlhttp=false 
    } 
    return xmlhttp; 
} 

function EnviarPressEnter(tecla){
  if(tecla==13) 
    document.forms[0].submit();
}

function Envia(){
  var d = document.forms[0];
  d.submit();
}

// Envia usando a Funcao Local 
function EnviarPressEnter2(tecla){
  if(tecla == 13) 
    sendForm();
}

if (navigator.appName.indexOf('Microsoft') != -1){
	clientNavigator = "IE";
 }else{
	clientNavigator = "Other";
 }

function vai (url){
  location.replace(url);
}

function msgRetorno (msg,url){
  alert(msg);		
  location.replace(url);
}


function popupLogin(url,urlRetorno){
   window.open(url,'Tela', 'scrollbars=yes, status=yes, fullscreen=yes');
   if (urlRetorno)
     location.href = urlRetorno;   
}

function ShowOpenModal(url,nome,w,h){
  window.showModalDialog(url,nome,'dialogWidth:'+w+'px;dialogHeight:'+h+'px');
}

function popup(url,w,h,l,t,urlRetorno,nomePagina){
   var width = w;
   var height = h;
   var left = l;
   var top = t;
   var top = (screen.height-w)/2; 
   var left = (screen.width-h)/2;  
 
   win =  window.open(url,nomePagina,'width='+width+', height='+height+', top='+top+', left='+left+', scrollbars=yes, status=yes, fullscreen=no').focus();
   if (urlRetorno)
     location.href = urlRetorno;   
}

function validaCampos() {
   var i = 0;
   var obj;
   var f = document.form1;
   //Conta os imputs
   for (i=0; i<f.elements.length; i++) {
     //comta quais os imputs que não foram selecionados....
	 obj = f.elements[i];
     if(obj.id != 1){
	    if(f.elements[i].value == "") {
           alert('O Campo ' + obj.id + ' não foi preenchido!');
           return false;
 		}    
	 }
  }
  f.submit();
}

//formata numero de valor em js

function fdp(n,d){
	var xx = n.indexOf('.')
	var l = n.length
	var zstr = '0000000000000000000000'
	var theInt = ''
	var theFrac = ''
	var theNo = ''
	rfac = ''
	rfacx = 0
	nx = 0
	var xt = parseInt(d) + 1
	var rstr = '' + zstr.substring(1,xt)
	var rfac = '.' + rstr + '5'
	var rfacx = parseFloat(rfac)
	if (xx == -1 ) 	{    // No fraction
		theFrac = zstr
		theInt = "" + n
	}
	else if (xx == 0) {
		theInt = '0'
		nx = 0 + parseFloat(n) + parseFloat(rfacx)
		n = nx + zstr
		theFrac = '' + n.substring(1, n.length)
	}
	else {
		theInt = n.substring(0,xx)
		nx = parseFloat(n) + rfacx
		n = '' + nx + zstr
		theFrac = '' + n.substring(xx+1,xx + 1 + parseInt(d))
		var astr = 'd = ' + d
	}
	theFrac = theFrac.substring(0,parseInt(d))
	var ii = 0
	theNo = theInt + '.' + theFrac
	return theNo
}
// JavaScript Document
/////////////////////////////////////////////////////////////////////////////////////////////////////
function validaData(str) { 

	dia = (str.value.substring(0,2)); 
    mes = (str.value.substring(3,5)); 
	ano = (str.value.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."); 
		str.value = "";
		str.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.value); 
		str.value = "";
		str.focus(); 
		return false;
	} 
}

// 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;
}

function getValue(nome){
   var obj = eval("document.forms[0]."+nome+".value");
   return obj;
}
function setValue(nome, valor){
   obj = eval("document.forms[0]."+nome);
   obj.value = valor;
}

/////////////Valores em dinheiro
function Limpar(valor, validos){
// retira caracteres invalidos da string
   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);
}

// Funcao CheckBox 
function selecionar2() {
    var campo = document.form2.elements['campo'];
	var varChecked =  document.form2.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(){
   var d = document.getElementById("email");
   if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(d.value)) || !d.value) 
     return false;
   else 
     return true;
}

function checkEmail2(email){
   if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)) || !email) 
     return false;
   else 
     return true;
}

function marcaCadastro(){
   if(document.form1.cadastros.checked == true){   
      for(var i=0; i<document.form1.elements.length; i++){
         if(document.form1.elements[i].id=="permissao"){
            document.form1.elements[i].checked=true;
		 }
	  }
   }
   else{
      for(var i=0; i<document.form1.elements.length; i++){
         if(document.form1.elements[i].id=="permissao"){
            document.form1.elements[i].checked=false;
		 }
	  }   
   }	  
}

function marcaCheckAll(){
   if(document.form1.todos.checked == true){   
      for(var i=0; i<document.form1.elements.length; i++){
         if(document.form1.elements[i].id=="caixa"){
            document.form1.elements[i].checked=true;
		 }
	  }
   }
   else{
      for(var i=0; i<document.form1.elements.length; i++){
         if(document.form1.elements[i].id=="caixa"){
            document.form1.elements[i].checked=false;
		 }
	  }   
   }	  
}

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 imprimir(){
/*  window.onbeforeprint = function() { 
    document.getElementById('lMenus').style.display="none";
  }
  window.onafterprint = function() { 
    document.getElementById('lMenus').style.display="block";
  } */
  document.getElementById('lMenus').style.display="none";  
  window.parent.focus();
  window.parent.print();
}

function checkForm(){
   if (form1.senha.value != form1.resenha.value){
      alert("As senhas nao conferem");
      form1.senha.value = "";
      form1.resenha.value = "";
      return (false);
   }else 
     return true;
}


function checkSenhas(){
   var senha 	= document.getElementById("senha").value;
   var re_senha = document.getElementById("re_senha").value;
   if (senha != re_senha){
      	alert("As senhas não conferem!");
   		document.getElementById("re_senha").value = "";
	   	document.getElementById("senha").value = "";
      	return false;
   } else 
     	return true;
}

//----------------------------------------------------
//Adciona uma nova linha quando o usario clicar em +
function addLinhaP() {

    var volta   = document.getElementById("tabela").rows.length; 
  	var tdSel   = ''; // Usado pra concatenar os esquema
  	var tbody  	= document.getElementById("tabela").getElementsByTagName("TBODY")[0];
  	var row    	= document.createElement("TR");
  	var td0    	= document.createElement("TD");
  	var td1    	= document.createElement("TD");
  	var td2    	= document.createElement("TD");
  	var td3    	= document.createElement("TD");
      
  	// Cor da linha 
  	row.setAttribute("className","td01");
	td0.innerHTML = '<input type=hidden id="id_produto'+volta+'" name="id_produto[]"><input name="prod[]" onKeyUp="listProd(this,'+volta+')"  id="textbox'+volta+'" size=45>';
  	td0.setAttribute("width","62%");
  	row.appendChild(td0);
  	
  	td1.innerHTML = "<input type='text' id='qtd"+volta+"' name='qtd[]' size='10' >";
  	td1.setAttribute("width","13%");
  	row.appendChild(td1);
  	
  	td2.innerHTML = "<input type='text' id='qtd_estoque"+volta+"' name='qtd_estoque[]'  size='10'>";
  	td2.setAttribute("width","17%");
  	row.appendChild(td2);
	
	var bb = "addLinhaP()";
  	td3.innerHTML = '<div align=center><a href="#" onclick="'+bb+'">+</a></div>';				
  	td3.setAttribute("width","8%");
  	td3.setAttribute("className","td00");	
  	row.appendChild(td3);

  	tbody.appendChild(row);
}
//----------------------------------------------------------
// Remove linha de qualquer tabelas pela qual foi criada 

function remLinha(tabela) {
    var table   = document.getElementById(tabela);
	if (table.rows.length-1 >0){
		var linha = table.rows.length; 
		table.deleteRow(linha-1);
	}
} // End deleteRows function

function Excluir(caminho,desc_nome,id,tabela,campo_tabela,op,urlRetorno,pasta,foto)
  {
    if(window.confirm("Confirma a exclusao de "+desc_nome))
      {
       location.href = caminho+"?id="+id+"&tabela="+tabela+"&campo_tabela="+campo_tabela+"&urlRetorno="+urlRetorno+"&op="+op+"&pasta="+pasta+"&foto="+foto;;
      } 
  } // Fim da Função 


function msgOpcao(msg,caminho,desc_nome,id,tabela,campo_tabela,op,urlRetorno){
    if(window.confirm(msg+desc_nome))
       location.href = caminho+"?id="+id+"&tabela="+tabela+"&campo_tabela="+campo_tabela+"&urlRetorno="+urlRetorno+"&op="+op;
} // Fim da Função 

 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 Verifica_Cep(cep, obrigatorio){
 //Se o parâmetro obrigatório for igual à zero, significa que elepode estar vazio, caso contrário, não
 	var cep    = document.getElementById(cep);
 	var strcep = cep.value;
 	if((obrigatorio == 1) || (obrigatorio == 0 && strcep != "")){
 		if (strcep.length != 9){
 			alert("CEP informado inválido.");
 			cep.focus();
 			return false
 		}else{
 			if (strcep.indexOf("-") != 5){
 				alert("Formato de CEP informado inválido.");
 				cep.focus();
 				return false
 			}else{
 				if (isNaN(strcep.replace("-","0"))){
 					alert("CEP informado inválido.");
 					cep.focus();
 					return false
 				}
 			}
 		}
 	}	  
 }

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;
	return window.open(url, nome, str);
}

// Nova Janela com Retorno 
function janelaCenterCR(url, nome, parms, width, height,urlRetorno) {
 	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;
	window.open(url, nome, str);
    if (urlRetorno)
     location.href = urlRetorno;   
}

function format_valor(valor){
  if (valor!='') 
	{
	  var valor   = valor.replace(".","");
	  var valor   = valor.replace(",",".");						   			  	
	  return valor;
	} else {
	  return 0;
	}
}									  

function totalOS(){
  var d = document;
  var tot = 0.00;
  var frete   = format_valor(document.getElementById("frete").value);	   
  var servico = format_valor(document.getElementById("servico").value);
  var sinal   = format_valor(document.getElementById("sinal").value);  
  tot  =  ((parseFloat(frete)+ parseFloat(servico)) - parseFloat(sinal));
  tot = new String(tot);
  d.getElementById('total').value  =  numberFormat(tot,20,2);
}


/**************************************************************************************************************************

function imprime_lpt1(arg1)
Descricao:  Funcao responsavel pela impressao diretamente na porta lpt1.

Requisitos: Internet Explorer superior que 5.0, mas nao testado no 5.5, testado e funcionando no 6.0.
			Nao testado em outros browsers

			****** IMPORTANTISSIMO ******
			Se estas alteracoes nao forem feitas, a impressao nao ocorrera corretamente.
			Alteracao das configuracoes de seguranca do navegador:
			Ferramentas -> Opcoes de Internet -> Seguranca ->
			Intranet local -> Nivel Personalizado ->
			Iniciar e executar scripts de controle ActiveX nao marcados como seguro -> Ativar
			Caso nao funcione:
			Internet -> Nivel Personalizado ->
			Iniciar e executar scripts de controle ActiveX nao marcados como seguro -> Ativar

Entrada:    Linha que sera impressa na autenticacao ou o comprovante de pagamento.

Saida:      Impressao em impressora fiscal do argumento de entrada.

**************************************************************************************************************************/
/*
function imprime_lpt1(arg1) {
	//Cria objeto para manipulacao de arquivos no cliente.
	var fso = new ActiveXObject("Scripting.FileSystemObject");
	//Verifica a existencia do arquivo de impressao antigo e o deleta;
	if ( fso.FileExists("c:\\temp\\imprime.prn") ) {
		fso.DeleteFile("c:\\temp\\imprime.prn");
	} //if
	//Verifica a nao existencia do arquivo responsavel pela impressao na impressora bematech.
	if ( !(fso.FileExists("c:\\temp\\imprime.bat")) ) {
		//Cria o arquivo imprime.bat, escreve o comando responsavel pela impressao e fecha o arquivo.
		var b = fso.CreateTextFile("c:\\temp\\imprime.bat", true);
		b.WriteLine("type c:\\temp\\imprime.prn > prn");
		b.Close();
	} //if
	//Cria o arquivo imprime.prn, escreve todo o texto para ser impresso e fecha o arquivo.
	var a = fso.CreateTextFile("c:\\temp\\imprime.prn", true);
	a.WriteLine(arg1);
	a.Close();
	//Cria um objeto para execucao de um programa no computador do cliente.
	var WshShell = new ActiveXObject("WScript.Shell");
	//Executa o arquivo responsavel pela impressao do arquivo imprime.prn.
	var oExec = WshShell.Exec("c:\\temp\\imprime.bat");
} //Fim do imprime_lpt1
*/

function imprime_lpt1(arg1) {
	//Cria objeto para manipulacao de arquivos no cliente.
//	var	caminho = "c:\\temp\\";
	var	caminho = "\\suporte\C\Temp";
	var fso = new ActiveXObject("Scripting.FileSystemObject");
	//Verifica a existencia do arquivo de impressao antigo e o deleta;
	if ( fso.FileExists(caminho+"imprime.prn") ) {
		fso.DeleteFile(caminho+"imprime.prn");
	} //if
	//Verifica a nao existencia do arquivo responsavel pela impressao na impressora bematech.
	if ( !(fso.FileExists(caminho+"imprime.bat")) ) {
		//Cria o arquivo imprime.bat, escreve o comando responsavel pela impressao e fecha o arquivo.
		var b = fso.CreateTextFile(caminho+"imprime.bat", true);
		b.WriteLine("type "+caminho+"imprime.prn > prn");
		b.Close();
	} //if
	//Cria o arquivo imprime.prn, escreve todo o texto para ser impresso e fecha o arquivo.
	var a = fso.CreateTextFile(caminho+"imprime.prn", true);
	a.WriteLine(arg1);
	a.Close();
	//Cria um objeto para execucao de um programa no computador do cliente.
	var WshShell = new ActiveXObject("WScript.Shell");
	//Executa o arquivo responsavel pela impressao do arquivo imprime.prn.
	var oExec = WshShell.Exec(caminho+"imprime.bat");
} //Fim do imprime_lpt1

// 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++){
  	 if (d.getElementById(campo[i]).value == ""){
    	alert ("Campo "+nome[i]+" esta em branco!");
	 	d.getElementById(campo[i]).focus();
	 	return false;
     }
	 if (campo[i] == "email" || campo[i] == "emailamigo"){
	 	if (!checkEmail2(d.getElementById(campo[i]).value)){
    		alert ("Campo "+nome[i]+" esta incorreto!");
	 		d.getElementById(campo[i]).focus();	 
			return false;
	 	}
	 }
  }
  return true;
}

// Fechar Janela 
function fechaJanela(){
  top.window.close();
}

function msgRetornoOpener(msg,url){
  alert(msg);		
  fechaJanela(); // Fecha a Janela Atual
  opener.location.href = url; // Carrega a janela que abriu o POPUP 
}
function msgFecha(msg){
  alert(msg);		
  fechaJanela(); // Fecha a Janela Atual
 }

function cancelar(){
   document.form1.reset();
   return false;
}

function voltar(){
   history.back();
}


// Verifica se a srting eh um numero 
function isNum(str){
	var VBlnIsNum;
	VIntTam = str.length;
	VBlnIsNum = true;
	if (VIntTam == 0){
		return false;
	} else {
		for (i=0; i < VIntTam; i++){
			if (str.substring(i,i+1) < '0' || str.substring(i,i+1) >'9'){
				VBlnIsNum = false;
			}
		}
		return VBlnIsNum;	
	}
}

//Função de validação de CPF
function isCPF(st) {
	st = st.replace( "-", "" );
	st = st.replace( "/", "" );
	st = st.replace( ".", "" );
	st = st.replace( ".", "" );
	
	switch (st){
		case '11111111111' :	return false;	break;
		case '22222222222' :	return false;	break;
		case '33333333333'  :	return false;	break;
		case '44444444444'  :	return false;	break;
		case '55555555555'  :	return false;	break;
		case '66666666666'  :	return false;	break;
		case '77777777777'  :	return false;	break;
		case '88888888888'  :	return false;	break;
		case '99999999999'  :	return false;	break;
		case '00000000000'  :	return false;	break;
	}
	
	if (st == "")
		return (false);
		l = st.length;
//aleterado para se usuário não digitar os zeros na frente do CPF, completar sozinho
	if ((l == 9) || (l == 8)){
		for (i = l ; i < 10; i++){
			st = '0' + st	
		}
	}
	l = st.length;
	st2 = "";
	for (i = 0; i < l; i++) {
		caracter = st.substring(i,i+1);
		if ((caracter >= '0') && (caracter <= '9'));
			st2 = st2 + caracter;
		}
	if ((st2.length > 11) || (st2.length < 10))
		return (false);
	if (st2.length==10)
		st2 = '0' + st2;
	digito1 = st2.substring(9,10);
	digito2 = st2.substring(10,11);
	digito1 = parseInt(digito1,10);
	digito2 = parseInt(digito2,10);
	sum = 0; mul = 10;
	for (i = 0; i < 9 ; i++) {
		digit = st2.substring(i,i+1);
		tproduct = parseInt(digit ,10) * mul;
		sum += tproduct;
		mul--;
	}
	dig1 = ( sum % 11 );
	if ( dig1==0 || dig1==1 )
		dig1=0;
	else
		dig1 = 11 - dig1;
	if (dig1!=digito1)
		return (false);
	sum = 0;
	mul = 11;
	for (i = 0; i < 10 ; i++) {
		digit = st2.substring(i,i+1);
		tproduct = parseInt(digit ,10)*mul;
		sum += tproduct;
		mul--;
	}
	dig2 = (sum % 11);
	if ( dig2==0 || dig2==1 )
		dig2=0;
	else
		dig2 = 11 - dig2;
	if (dig2 != digito2)
		return (false);
	return (true);
}

function $get(idElemento){
	return document.getElementById(idElemento);
}
// 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 DateString(){
	var Hoje = new Date();
	var strData = Dia(Hoje.getDay()) + ", " + Hoje.getDate();
	strData += " de " + Mes(Hoje.getMonth()) + " de " + Hoje.getYear();
	return strData
}	

function selWebmail(qual){
	if(qual == 'novo'){
		document.fWebmail.method = '';
		document.fWebmail.action = '';
		document.fWebmail.onsubmit = new Function('Ext_Login.loginform(this); return false;');
	} else {
		document.fWebmail.method = 'get';
		document.fWebmail.action = 'http://mx.bommtempo.com.br/mail/login.html';
		document.fWebmail.onsubmit = '';
	}
}