// JavaScript Document

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 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 "";
}	

function abrir_popup(url,w,h,s){	
	var popup = window.open(url,'popup','width='+w+',height='+h+',resizable=0,status=0,menubar=0,scrollbars=1');
}

function muda_tamanho_texto (elem, acao){    
	var tamInic = 12;    
	var tamMin = 12;    
	var tamMax = 18;    
	
	if (document.getElementById(elem).style.fontSize == "") {            
		var tamFonte = tamInic;    
	} else{            
		var tamFonte = parseInt(document.getElementById(elem).style.fontSize);            
	  }            
	
	switch (acao){                
		case '+':                        
			if (tamFonte < tamMax)                                
				document.getElementById(elem).style.fontSize = (tamFonte + 2) + "px";                
				break;                
		case '-':                        
			if (tamFonte > tamMin)                                
				document.getElementById(elem).style.fontSize = (tamFonte - 2) + "px";                
			break;            
	}
}

// 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 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 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.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  ) );
			   } 	 			
		  }
	  }
 }

 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  = 'ABCDEFGHIJKLMNOPQRSTUVWXYZÇabcdefghijklmnopqrstuvwxyzç';
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;
 
 if (tecla == '') return false;

 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 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, 'AAA-####');
}