// JavaScript Document

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);
	}
	document.getElementById(id).innerText = 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.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');
  	  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.';  
				   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;

}
