// JavaScript Document

var default_value = '-- Selecione --';
var _default_value = '-- Selecione --';

function fnc_limpa_select( p_select ) {
  for( var i = ( p_select.options.length - 1 ); i >= 0; i-- ) p_select.options[ i ] = null;
   p_select.selectedIndex = -1;
}

function pega_municipio_ajax(estado_id, select_destino, municipio_id, busca){

   if ( busca && busca != '' && busca == 0 )
   		default_value = '-- Todos --';
	
   municipio_session = municipio_id;
   if (document.getElementById(select_destino)){
	   elemento_form = document.getElementById(select_destino);
	   fnc_cria_option( elemento_form, '', 'carregando...', true );
   }
   if ( estado_id != '' ){
	   param = 'estado_id='+estado_id;
	   http( 'POST' , '_cfc/_ajax_gerais.cfc?method=pega_municipio' , pega_municipio_ajax_retorno , param ); 
   } else { 
	 fnc_limpa_select(elemento_form);
	 fnc_cria_option( elemento_form, '', default_value, true );
   }
}

function pega_municipio_ajax_retorno(obj){ 

if (elemento_form){
	 fnc_limpa_select(elemento_form);
	 fnc_cria_option( elemento_form, '', default_value, true );

	for( var i = 0; i < obj.length; i++ ) {
		valor = obj[i].municipio_id.toString();
		label = obj[i].municipio;
		if (municipio_session && municipio_session != '' && valor == municipio_session){
			selected = true;
		} else { selected = false; }
		fnc_cria_option( elemento_form, valor, label, selected );
	 }
	  
	  /* habilita o elemento */
	  elemento_form.disabled = false;
	  /* -- */
  }
	  
}

function pega_bairro_ajax(_municipio_id, _select_destino, _bairro_id, _busca){

   if ( _busca && _busca != '' && _busca == 0 )
   		_default_value = '-- Todos --';
	
   _bairro_session = _bairro_id;
   if (document.getElementById(_select_destino)){
	   _elemento_form = document.getElementById(_select_destino);
	   fnc_cria_option( _elemento_form, '', 'carregando...', true );
   }
   if ( _municipio_id != '' ){
	   param = 'municipio_id='+_municipio_id;
	   http( 'POST' , '_cfc/_ajax_gerais.cfc?method=pega_bairro' , pega_bairro_ajax_retorno , param ); 
   } else { 
	 fnc_limpa_select(_elemento_form);
	 fnc_cria_option( _elemento_form, '', _default_value, true );
   }
}

function pega_bairro_ajax_retorno(obj){ 

if (_elemento_form){
	 fnc_limpa_select(_elemento_form);
	 fnc_cria_option( _elemento_form, '', _default_value, true );

	for( var i = 0; i < obj.length; i++ ) {
		valor = obj[i].bairro_id.toString();
		label = obj[i].bairro;
		if (_bairro_session && _bairro_session != '' && valor == _bairro_session){
			selected = true;
		} else { selected = false; }
		fnc_cria_option( _elemento_form, valor, label, selected );
	 }
	  
	  /* habilita o elemento */
	  elemento_form.disabled = false;
	  /* -- */
  }
	  
}

function pega_bairro_ajax_iframe(municipio_id, select_destino, bairro_id, busca){
   if ( busca && busca != '' && busca == 0 )
   		default_value = '-- Todos --';
	
   bairro_session = bairro_id;
   if (parent.document.getElementById(select_destino)){
	   elemento_form = parent.document.getElementById(select_destino);
	   fnc_cria_option( elemento_form, '', 'carregando...', true );
   }
   if ( municipio_id != '' ){
	   param = 'municipio_id='+municipio_id;
	   http( 'POST' , '../_cfc/_ajax_gerais.cfc?method=pega_bairro' , pega_bairro_ajax_iframe_retorno , param ); 
   } else { 
	 fnc_limpa_select(elemento_form);
	 fnc_cria_option( elemento_form, '', default_value, true );
   }
}

function pega_bairro_ajax_iframe_retorno(obj){ 

if (elemento_form){
	 fnc_limpa_select(elemento_form);
	 fnc_cria_option( elemento_form, '', default_value, true );

	for( var i = 0; i < obj.length; i++ ) {
		valor = obj[i].bairro_id.toString();
		label = obj[i].bairro;
		if (bairro_session && bairro_session != '' && valor == bairro_session){
			selected = true;
		} else { selected = false; }
		fnc_cria_option( elemento_form, valor, label, selected );
	 }
	  
	  /* habilita o elemento */
	  elemento_form.disabled = false;
	  /* -- */
  }
	  
}

function pega_unidade_ajax(emp_id, select_destino, unidade_id, busca){

   if ( busca && busca != '' && busca == 0 )
   		default_value = '-- Todas --';
	
   unidade_session = unidade_id;
   if (document.getElementById(select_destino)){
	   elemento_form = document.getElementById(select_destino);
	   fnc_cria_option( elemento_form, '', 'carregando...', true );
   }
   if ( emp_id != '' ){
	   param = 'emp_id='+emp_id;
	   http( 'POST' , '_cfc/_ajax_gerais.cfc?method=pega_unidade' , pega_unidade_ajax_retorno , param ); 
   } else { 
	 fnc_limpa_select(elemento_form);
	 fnc_cria_option( elemento_form, '', default_value, true );
   }
}

function pega_unidade_ajax_retorno(obj){ 

if (elemento_form){
	 fnc_limpa_select(elemento_form);
	 fnc_cria_option( elemento_form, '', default_value, true );

	for( var i = 0; i < obj.length; i++ ) {
		valor = obj[i].unidade_id.toString();
		label = obj[i].unidade;
		if (unidade_session && unidade_session != '' && valor == unidade_session){
			selected = true;
		} else { selected = false; }
		fnc_cria_option( elemento_form, valor, label, selected );
	 }
	  
	  /* habilita o elemento */
	  elemento_form.disabled = false;
	  /* -- */
  }
	  
}

function limpa_formulario(form){
    for(i=0;i<form.length;i++){
        elemento = form[i];
        tipo = elemento.type;
        if (tipo == 'text' || tipo == 'password' || tipo == 'textarea')
          elemento.value = '';
        else if (tipo == 'checkbox' || tipo == 'radio')
          elemento.checked = false;
        else if (tipo == 'select-one' || tipo == 'select')
          elemento.selectedIndex = '';
    }
}

function fnc_verifica_senhas_iguais2(form){

	if ( fnc_verifica_form(form) ){
		if (document.getElementById('senha2').value != document.getElementById('rp_nova_senha2').value){
			alert('Senha e confirmação de senha não conferem. Tente novamente!');
			document.getElementById('senha2').value = '';
			document.getElementById('rp_nova_senha2').value = '';
			document.getElementById('senha2').focus();
			return false;
			
		} else { return true; }
	} else { return false; }
}

function fnc_escolhe_cidade(estado_id){

	for( var i = ( document.getElementById('municipio_id').options.length - 1 ); i >= 0; i-- ) document.getElementById('municipio_id').options[ i ] = null;
	//top.location='carrega_cidades.cfm?estado_id='+estado_id;
	document.getElementById('iframe').src='carrega_cidades.cfm?estado_id='+estado_id;
	
}

function fnc_escolhe_cidade_edicao(estado_id, municipio_id){

	for( var i = ( document.getElementById('municipio_id').options.length - 1 ); i >= 0; i-- ) document.getElementById('municipio_id').options[ i ] = null;
	//top.location='carrega_cidades.cfm?estado_id='+estado_id+'&municipio_id='+municipio_id;
	document.getElementById('iframe').src='carrega_cidades.cfm?estado_id='+estado_id+'&municipio_id='+municipio_id;
	
}

// Cria option no selectbox
function fnc_cria_option( p_select, p_valor, p_texto, p_selected ) {
	if( p_select != null && p_select.options != null )
	p_select.options[ p_select.options.length ] = new Option( p_texto, p_valor, false, p_selected );
}
// remove option do selectbox
function fnc_deleta_componente( p_obj_origem , j ) {
	p_obj_origem.options[ j ] = null;
}

function Contar(Campo,id,qtd_caracteres){

	if((qtd_caracteres-Campo.value.length) <= 0){
	   alert('Atenção! Você atingiu o limite máximo de '+qtd_caracteres+' caracteres!');
	   Campo.value = Campo.value.substr(0,qtd_caracteres);
	}
	//alert(document.getElementById(id))
	document.getElementById(id).innerHTML = qtd_caracteres-Campo.value.length
}

function swapBG( el, BG1, BG2 ){
  el.style.backgroundColor = ( el.style.backgroundColor == BG1 ) ? BG2 : BG1;
}

function vai_para(pagina){
  document.form_vai_para.action = pagina;
  document.form_vai_para.target = '_blank';
  document.form_vai_para.submit();	
}

function fnc_verifica_senhas_iguais(form){
	if ( fnc_verifica_form(form) ){
		if (document.getElementById('nova_senha').value != document.getElementById('rpt_nova_senha').value){
			alert('Senha e confirmação de senha não conferem. Tente novamente!');
			document.getElementById('nova_senha').value = '';
			document.getElementById('rpt_nova_senha').value = '';
			document.getElementById('nova_senha').focus();
			return false;
			
		} else { return true; }
	} else { return false; }
}
		
function qtd_min_checkBox(elemento){

	lista = elemento; //formNoticiasParaDestaqueNoticias.lista
	//alert(input_check_box);
	alert('aqui');
	alert(elemento.checked);
	alert(elemento.value);
	contador = 0;

	for (p=0 ; p < lista.length; p++){
		if (lista[p].checked) {
			//alert(lista[i].value);
			contador++;
		}
	}
alert(contador);
	if ( contador > elemento.num_max ) {
		alert('Número máximo ( '+elemento.num_max+' ) de notícias destaque alcançado! Tente Novamente !'); 
		return ( false );
	}
	if ( contador < elemento.num_min ) {
		alert('Pelo menos '+elemento.num_min+ ' elemento(s) devem ser selecionados'); 
		return ( false );
	}
	
	
	return ( true );
	
}




function getMsec(data){
	if(!isDate(data))return 0;
	if(data instanceof Date)return data.valueOf();
	var dt = data.replace(/[\/\.\-]/g,"-").split("-");
	return (new Date(dt[2],--dt[1],dt[0]).valueOf());	
}	

 
function isDate(data){
	if(data instanceof Date)return true;
	var adt = data.replace(/[\s\:\/\.\-]/g,"-").split("-");
	if(adt.length>3){
		var odt = new Date(adt[2],--adt[1],adt[0],adt[3],adt[4]);
		var hr = (odt.getHours()==adt[3] && odt.getMinutes()==adt[4]);
	}else 
		var odt = new Date(adt[2],--adt[1],adt[0]);		
	var dt = (odt.getFullYear()==adt[2] && odt.getMonth()==adt[1] && odt.getDate()==adt[0]);
	return (adt.length>3) ? dt && hr : dt;
}

<!-- Highlight de elementos do form -->

var highlightcolor="#EEEFF0"

var ns6=document.getElementById&&!document.all
var previous=''
var eventobj

//Regular expression to highlight only form elements
var intended=/INPUT|TEXTAREA|SELECT|OPTION/

//Function to check whether element clicked is form element
function checkel(which){
	if (which.style&&intended.test(which.tagName)){
			if (ns6&&eventobj.nodeType==3)
				eventobj=eventobj.parentNode.parentNode
		return true
	} else
		return false
}

//Function to highlight form element
/*
function highlight(e){
	eventobj=ns6? e.target : event.srcElement
	if (previous!=''){
		if (checkel(previous))
	previous.style.backgroundColor=''
	previous=eventobj
	if (checkel(eventobj))
		eventobj.style.backgroundColor=highlightcolor
	} else{
		if (checkel(eventobj))
			eventobj.style.backgroundColor=highlightcolor
	  previous=eventobj
	}
}
*/
<!-- fim de Highlight de elemntos do form -->

function expande_objeto(id, ponteiro){
	
	if ( ponteiro ){
		/*alert(document.getElementById(ponteiro).className);*/
		document.getElementById(ponteiro).className=='visivel' || document.getElementById(ponteiro).className=='' ? document.getElementById(ponteiro).className='invisivel' : document.getElementById(ponteiro).className='visivel';
	}
	
	document.getElementById(id).className=='visivel' ? parent.document.getElementById(id).className='invisivel' : parent.document.getElementById(id).className='visivel';
}

function expande_objeto_inxex(id, ponteiro, busca){
	document.getElementById(id).className=='visivel' ? document.getElementById(id).className='invisivel' : document.getElementById(id).className='visivel';
	
	if ( ponteiro ){
		/*alert(document.getElementById(ponteiro).className);*/
		document.getElementById(id).className=='invisivel' ? document.getElementById(ponteiro).className='visivel' : document.getElementById(ponteiro).className='invisivel';
	}
	if ( busca ){
		/*alert(document.getElementById(ponteiro).className);*/
		document.getElementById(id).className=='invisivel' ? document.getElementById(busca).className='visivel' : document.getElementById(busca).className='invisivel';
	}
}


<!-- PARA VALIDAÇÃO DE FORMULÁRIO -->

Date.prototype.Dtos = function() {
  var dd = this.getDate();
  var mm = this.getMonth() + 1;
  var yy = this.getFullYear();
	
  return( [ yy , ( mm < 10 ? '0' : '' ) + mm , ( dd < 10 ? '0' : '' ) + dd ].join( '' ) );
}

Array.prototype.hasEmptyElements = function() {
  for( var i = 0 ; i < this.length ; i++ )
   if( ( this[ i ] == '' ) || ( this[ i ] == null ) || ( this[ i ] == undefined ) )
	  return( true );
			
   return( false );
}

String.prototype.isNumber = function() {
  return( !isNaN( this.split( '.' ).join( '' ).split( ',' ).join( '' ).split( '-' ).join( '' ) ) );
}

String.prototype.isDate = function() {
  if( this.split( '/' ).length != 3 ) return( false );

   var dd = Number( this.split( '/' )[ 0 ] );
   var mm = Number( this.split( '/' )[ 1 ] );
   var yy = Number( this.split( '/' )[ 2 ] );
   var dt = new Date( yy , mm -1 , dd  );
	
  return( [ yy , ( mm < 10 ? '0' : '' ) + mm , ( dd < 10 ? '0' : '' ) + dd ].join( '' ) == dt.Dtos() );
}

String.prototype.isMail = function() {
 var test;
 var pt1    = this.split( '@' );
 var valid  = '.-_@';
		
	if( ( pt1.length != 2 ) || ( pt1[ 0 ].length == 0 ) || ( pt1[ 1 ].length == 0 ) ) 
		return( false );
	else {
	  for( var i = 0 ; i < valid.length - 1 ; i++ ) {
		if( pt1[ 0 ].split( valid.charAt( i ) ).hasEmptyElements() ) return( false );
		if( pt1[ 1 ].split( valid.charAt( i ) ).hasEmptyElements() ) return( false );
	   }			
	}
	for( var i = 0 ; i < this.length ; i++ ) {
	  var charac = this.toUpperCase().charCodeAt( i );
	  
		if( valid.indexOf( String.fromCharCode( charac ) ) == -1 )
		if(!( ( ( charac >= 65 ) && ( charac <= 90 ) ) || ( ( charac >= 48 ) && ( charac <= 57 ) ) ) ) 
		   return( false );
	}	
	
  return( true );
}

String.prototype.isCNPJ = function() {
 var b = [6,5,4,3,2,9,8,7,6,5,4,3,2], c = this;

  if((c = c.replace(/[^\d]/g,"").split("")).length != 14) return ( false );
  for(var i = 0, n = 0; i < 12; n += c[i] * b[++i]);
  if(c[12] != (((n %= 11) < 2) ? 0 : 11 - n)) return ( false );
  for(var i = 0, n = 0; i <= 12; n += c[i] * b[i++]);
  if(c[13] != (((n %= 11) < 2) ? 0 : 11 - n)) return ( false );

  return ( true );
}

function fnc_verifica_tipo( p_campo ) {
  if( p_campo && ( !p_campo.readOnly  || p_campo.type != 'button' || p_campo.type != 'hidden' ) ) return( false );
 return( true );																						   
}

function fnc_verifica_form( form ) {
 var showMessage = function(p_msg, p_campo ){ alert( p_msg ); /*if( tip ) tip.show( p_msg ); p_campo.className='requerido';*/ p_campo.focus();  return false; }
 var temSecao    = ( fnc_verifica_form.arguments.length == 2 )?true:false;
 var secao	     = ( temSecao )?fnc_verifica_form.arguments[ 1 ]:'';
 var mensagem    = '';

 for( var i = 0; i < form.length; i++ ) {
  	  var campo 	= form.elements[ i ];	  
  	  var tipo  	= campo.getAttribute('tipo');
  	  var requerido = campo.getAttribute('obrigatorio');	  
  	  var display	= campo.getAttribute('display');
	  if ( requerido )
		  var valor 	= campo.value.replace(/^\s*|\s*$/g,"");
  	  var erro	    = false ;
  
	  // verificação se existe seção ou não 
	  if ( ( temSecao && secao == campo.getAttribute('secao') ) || !temSecao )  { 
		  // se o campo for requerido
		  if ( requerido == 1 ) { 
		  	 // validação simples
    			if ( !valor ) {
				   mensagem =  'O campo ' + display + ' ' + String.fromCharCode( 233 ) + ' requerido.';
				   if (tipo == 'pelo_menos_um'){
						mensagem = mensagem + ' Inclua pelo menos um';
				   }
				   return( showMessage( mensagem , campo  ) );		
				} 
			    // validação dos tipos
			    if( tipo && valor ) { 
				   mensagem = 'O valor do campo ' + display + ' deve ser ';
					if( tipo == 'numerico' && !valor.isNumber() ){
					    erro = true;
					    mensagem += ' num' + String.fromCharCode( 233 ) + 'rico.';
					} else if ( tipo == 'data' && !valor.isDate() ) {
						erro = true;
						mensagem += ' uma data v' + String.fromCharCode( 225 ) + 'lida.';
				    } else if( tipo == 'email' && !valor.isMail() ){ 
						erro = true;
					 	mensagem += ' um e-mail v'+ String.fromCharCode( 225 )+'lido.';
				    } else if( tipo == 'cnpj' && !valor.isCNPJ()) {
					 	erro = true;
					 	mensagem += 'um CNPJ v' + String.fromCharCode( 225 ) + 'lido.';
				    } 
				   // mostra erro
				   if( erro ) return( showMessage( mensagem , campo  ) );
			   } 
			   /*campo.className='';*/
		  }
	  }
 }

 return ( true );
}


documentall = document.all;
/*
* função para formatação de valores monetários retirada de
* http://jonasgalvez.com/br/blog/2003-08/egocentrismo
*/

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;

}

/*
* Valida url no formato http://...
*
* @param  form  - formulario
* @return boolean - true se for valida
*
* @autor por Igor Meira
*/
function validaUrl(form){
	 var showMessage = function(p_msg, p_campo ){ alert( p_msg ); p_campo.focus();  return false; }
	var lCampo = document.getElementById('url');
	var mensagem    = '';
	if( trim(lCampo.value) != '') {
		var lHttp = lCampo.value.substr(0 , 7);
		if( lHttp != 'http://' ){
			mensagem += 'Url invalida! Não foi localizado o prefixo >> http:// <<';
			return( showMessage( mensagem , lCampo  ) );
		}//fim if
	} // fim if
	return ( true );
}//fim validaUrl 


function trim(string) {
	var valor = new String(string);

	while(valor.charAt(0) == " ") {
		valor = valor.replace(" ", "");
	} // fim while

	return valor;
} // fim trim

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 MaskCEP(objeto, evt) { 
return Mascara(objeto, evt, '#####-###');
}

function MaskCODIGO(objeto, evt) { 
return Mascara(objeto, evt, '######');
}

function MaskORCAMENTO(objeto, evt) { 
return Mascara(objeto, evt, '##########');
}

function MaskDATA(objeto, evt) { 
return Mascara(objeto, evt, '##/##/####');
}

function MaskTelefone(objeto, evt) { 
return Mascara(objeto, evt, '(##) ####-####');
}

function MaskCPF(objeto, evt) { 
return Mascara(objeto, evt, '###.###.###-##');
}

function MaskCNPJ(objeto, evt) { 
return Mascara(objeto, evt, '##.###.###/####-##');
}

function MaskPlacaCarro(objeto, evt) { 
return Mascara(objeto, evt, 'ZZZ-####');
}

function MaskNumeroIsotank(objeto, evt) { 
return Mascara(objeto, evt, 'ZZZZ ######-#');
}

function adicionar_favoritos(){ 
	
	var url = "http://www.centrocol.com.br/"; 
	var title = ".: Centro COL :."; 	
	
	if (window.sidebar) // firefox
		window.sidebar.addPanel(title, url, "");
	else if(window.opera && window.print){ // opera
		var elem = document.createElement('a');
		elem.setAttribute('href',url);
		elem.setAttribute('title',title);
		elem.setAttribute('rel','sidebar');
		elem.click();
	} 
	else if(document.all)// ie
	//alert(window.external)
		window.external.AddFavorite(url, title);
}

function MascaraMoeda(objTextBox, SeparadorMilesimo, SeparadorDecimal, 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 == 13 || whichCode == 8 || whichCode == 0) return true;
    key = String.fromCharCode(whichCode); // Valor para o código da Chave
    if (strCheck.indexOf(key) == -1) return false; // Chave inválida
    len = objTextBox.value.length;
    for(i = 0; i < len; i++)
        if ((objTextBox.value.charAt(i) != '0') && (objTextBox.value.charAt(i) != SeparadorDecimal)) break;
    aux = '';
    for(; i < len; i++)
        if (strCheck.indexOf(objTextBox.value.charAt(i))!=-1) aux += objTextBox.value.charAt(i);
    aux += key;
    len = aux.length;
    if (len == 0) objTextBox.value = '';
    if (len == 1) objTextBox.value = '0'+ SeparadorDecimal + '0' + aux;
    if (len == 2) objTextBox.value = '0'+ SeparadorDecimal + aux;
    if (len > 2) {
        aux2 = '';
        for (j = 0, i = len - 3; i >= 0; i--) {
            if (j == 3) {
                aux2 += SeparadorMilesimo;
                j = 0;
            }
            aux2 += aux.charAt(i);
            j++;
        }
        objTextBox.value = '';
        len2 = aux2.length;
        for (i = len2 - 1; i >= 0; i--)
        objTextBox.value += aux2.charAt(i);
        objTextBox.value += SeparadorDecimal + aux.substr(len - 2, len);
    }
    return false;
}
