function $K(id) { return document.getElementById(id); }
function handleKeyPress(evt) { var nbr;  var nbr = (window.event)?event.keyCode:evt.which;  return nbr; }
function Pooopup(pagina, largura, altura) {
	w = screen.width;
	h = screen.height;
	meio_w = w/2;
	meio_h = h/2;

	altura2 = altura/2;
	largura2 = largura/2;
	meio1 = meio_h-altura2;
	meio2 = meio_w-largura2;

	if(screen.width <= 1024) {
		window.open(pagina,'','height=' + altura + ', width=' + largura + ', top='+meio1+', left='+meio2+'');
	} else {
		window.open(pagina,'','height=' + altura + ', width=' + largura + ', top='+meio1+', left='+meio2+'');
	}
}
function PooopupAvaliacao(pagina, largura, altura) {
	w = screen.width;
	h = screen.height;
	meio_w = w/2;
	meio_h = h/2;

	altura2 = altura/2;
	largura2 = largura/2;
	meio1 = meio_h-altura2;
	meio2 = meio_w-largura2;

	if(screen.width <= 1024) {
		window.open(pagina,'','height=' + altura + ', width=' + largura + ', scrollbars=yes, top='+meio1+', left='+meio2+'');
	} else {
		window.open(pagina,'','height=' + altura + ', width=' + largura + ', scrollbars=yes, top='+meio1+', left='+meio2+'');
	}
}
function PooopupBanco(pagina, largura, altura) {
	w = screen.width;
	h = screen.height;
	meio_w = w/2;
	meio_h = h/2;

	altura2 = altura/2;
	largura2 = largura/2;
	meio1 = meio_h-altura2;
	meio2 = meio_w-largura2;

	if(screen.width <= 1024) {
		window.open(pagina,'','height=' + altura + ', width=' + largura + ', top='+meio1+', left='+meio2+'');
	} else {
		window.open(pagina,'','height='+screen.availHeight+', width='+screen.availWidth+', top='+0+', left='+0+'');
	}
}

function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}


	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

mostraMenu = function(id) {
	var obj = document.getElementById(id);
	obj.style.display = 'block';
}
escondeMenu = function(id) {
	var obj = document.getElementById(id);
	obj.style.display = 'none';
}
var tam = 12;
function mudaFonte(tipo,elemento){
	if (tipo=="mais") {
		if(tam<16) tam+=1;
	} else {
		if(tam>10) tam-=1;
	}
	document.getElementById('texto').style.fontSize = tam+'px';
	//document.getElementById('mudaFoto').style.fontSize = tam+'px';
}
function ativar(ativar,avisoidl) { 
	var Aviso = document.getElementById(avisoidl);
	if(ativar == 'sim') {
		Aviso.style.display= 'block';
	} else {
		Aviso.style.display = 'none';
	}
}
function validate(theForm) {
	if (theForm.nome2.value == "") { alert("Digite seu Nome!"); theForm.nome2.focus(); return (false); }
	if (theForm.email.value == "") { alert("Digite seu email!"); theForm.email.focus(); return (false); }
	if (theForm.email.value.search(/^\w+((-\w+)|(\.\w+))*\@\w+((\.|-)\w+)*\.\w+$/) == -1) { alert("E-mail inválido!"); theForm.email.focus(); return (false); }
	if (theForm.assunto.value == "") { alert("Digite o Assunto!"); theForm.assunto.focus(); return (false); }
	if (theForm.listEstado.value == "0") { alert("Selecione um Estado!"); theForm.listEstado.focus(); return (false); }
	if (theForm.listCidades.value == "0") { alert("Selecione a Cidade!"); theForm.listCidades.focus(); return (false); }
	if (theForm.departamento.value == "0") { alert("Selecione o Departamento!"); theForm.departamento.focus(); return (false); }
	if (theForm.mensagem.value == "") { alert("Digite a sua Mensagem!"); theForm.mensagem.focus(); return (false); }
	return (true);
}
function validarenviar(theFormAmigo) {
	if (theFormAmigo.nome2.value == "") { alert("Digite seu Nome!"); theFormAmigo.nome.focus(); return (false); }
	if (theFormAmigo.email.value == "") { alert("Digite seu E-mail!"); theFormAmigo.email.focus(); return (false); }
	if (theFormAmigo.email.value.search(/^\w+((-\w+)|(\.\w+))*\@\w+((\.|-)\w+)*\.\w+$/) == -1) { alert("E-mail inválido, digite corretamente!"); theFormAmigo.email.focus(); return (false); }
	if (theFormAmigo.nomepara.value == "") { alert("Digite o nome do seu amigo!"); theFormAmigo.nomepara.focus(); return (false); }
	if (theFormAmigo.emailpara.value == "") { alert("Digite o email do seu amigo!"); theFormAmigo.emailpara.focus(); return (false); }
	if (theFormAmigo.emailpara.value.search(/^\w+((-\w+)|(\.\w+))*\@\w+((\.|-)\w+)*\.\w+$/) == -1) { alert("E-mail inválido, digite corretamente!"); theFormAmigo.emailpara.focus(); return (false); }
	return (true);
}
var tam = 12;
function mudaFonte(tipo,elemento){
	if (tipo=="mais") {
		if(tam<16) tam+=1;
	} else {
		if(tam>10) tam-=1;
	}
	document.getElementById('texto').style.fontSize = tam+'px';
	//document.getElementById('mudaFoto').style.fontSize = tam+'px';
}
function getPageScroll(){

	var yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	}

	arrayPageScroll = new Array('',yScroll) 
	return arrayPageScroll;
}



function verifica(v){
	return((typeof(v)=='undefined' || v.length==0)?false:true);
}
function agent(v){
	return(Math.max(navigator.userAgent.toLowerCase().indexOf(v),0));
}
function XeYjanela(v){ 
	var z=agent('msie')?Array(document.body.clientHeight,document.body.clientWidth):Array(window.innerHeight,window.innerWidth); 
	return(verifica(v)?z[v]:z); 
} 
function abrelight(x,tam, tipo){//by Renan Henrique

var arrayPageSize = getPageSize();
var arrayPageScroll = getPageScroll();

var fundo = document.getElementById('over');
var div = document.getElementById(x);
	fundo.style.display='block';
	div.style.display='block';

	div.style.top = (arrayPageScroll[1] + ((arrayPageSize[3] - 35 - tam) / 2) + 'px');
	div.style.left = (((arrayPageSize[0] - 20 - tam) / 2) + 'px');

}
function fechalight(div){//by Renan Henrique
	
	var fundo = document.getElementById('over');	
	var div2 = document.getElementById(div);
	
	fundo.style.display='none';
	div2.style.display='none';

}

function vertamanho(){//by Renan Henrique
var fundo = document.getElementById('over');
	if(fundo.style.display=='block'){	
		abreWebMail();
	}
}

function abreWebMail(){//by Renan Henrique
	scrollTo(0,0);
	var div = 'webmail';
	var altu = 158;
	var larg = 308;
	var arrayPageSize = getPageSize();
	var arrayPageScroll = getPageScroll();
	
	var fundo = document.getElementById('over');
	var div_get = document.getElementById(div);		
	
	fundo.style.display='block';
	fundo.style.height = arrayPageSize[1];
	
	div_get.style.display='block';	
	div_get.style.top = (arrayPageScroll[1] + ((arrayPageSize[3] - 35 - altu) / 2) + 'px');
	div_get.style.left = (((arrayPageSize[0] - 20 - larg) / 2) + 'px');
}

function mascara(o,f){
    v_obj=o
    v_fun=f
    setTimeout("execmascara()",1)
}

function execmascara(){
    v_obj.value=v_fun(v_obj.value)
}

function leech(v){
    v=v.replace(/o/gi,"0")
    v=v.replace(/i/gi,"1")
    v=v.replace(/z/gi,"2")
    v=v.replace(/e/gi,"3")
    v=v.replace(/a/gi,"4")
    v=v.replace(/s/gi,"5")
    v=v.replace(/t/gi,"7")
    return v
}

function soNumeros(v){
    return v.replace(/\D/g,"")
}

function telefone(v){
    v=v.replace(/\D/g,"")                 //Remove tudo o que não é dígito
    v=v.replace(/^(\d\d)(\d)/g,"($1) $2") //Coloca parênteses em volta dos dois primeiros dígitos
    v=v.replace(/(\d{4})(\d)/,"$1-$2")    //Coloca hífen entre o quarto e o quinto dígitos
    return v
}

function itelefone(v){
    v=v.replace(/\D/g,"")                 //Remove tudo o que não é dígito
    v=v.replace(/^(\d\d)(\d)/g,"($1) $2") //Coloca parênteses em volta dos dois primeiros dígitos
    v=v.replace(/(\d{4})(\d)/,"$1-$2")    //Coloca hífen entre o quarto e o quinto dígitos
    return v
}

function cpf(v){
    v=v.replace(/\D/g,"")                    //Remove tudo o que não é dígito
    v=v.replace(/(\d{3})(\d)/,"$1.$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
    v=v.replace(/(\d{3})(\d)/,"$1.$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
                                             //de novo (para o segundo bloco de números)
    v=v.replace(/(\d{3})(\d{1,2})$/,"$1-$2") //Coloca um hífen entre o terceiro e o quarto dígitos
    return v
}
function cpfx(v){
    v=v.replace(/\D/g,"")                    //Remove tudo o que não é dígito
    v=v.replace(/(\d{3})(\d)/,"$1.$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
    v=v.replace(/(\d{3})(\d)/,"$1.$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
                                             //de novo (para o segundo bloco de números)
    v=v.replace(/(\d{3})(\d{1,2})$/,"$1-$2") //Coloca um hífen entre o terceiro e o quarto dígitos
    return v
}
function cep(v){
    v=v.replace(/D/g,"")                //Remove tudo o que não é dígito
    v=v.replace(/^(\d{5})(\d)/,"$1-$2") //Esse é tão fácil que não merece explicações
    return v
}

function cnpj(v){
    v=v.replace(/\D/g,"")                           //Remove tudo o que não é dígito
    v=v.replace(/^(\d{2})(\d)/,"$1.$2")             //Coloca ponto entre o segundo e o terceiro dígitos
    v=v.replace(/^(\d{2})\.(\d{3})(\d)/,"$1.$2.$3") //Coloca ponto entre o quinto e o sexto dígitos
    v=v.replace(/\.(\d{3})(\d)/,".$1/$2")           //Coloca uma barra entre o oitavo e o nono dígitos
    v=v.replace(/(\d{4})(\d)/,"$1-$2")              //Coloca um hífen depois do bloco de quatro dígitos
    return v
}

function romanos(v){
    v=v.toUpperCase()             //Maiúsculas
    v=v.replace(/[^IVXLCDM]/g,"") //Remove tudo o que não for I, V, X, L, C, D ou M
    //Essa é complicada! Copiei daqui: http://www.diveintopython.org/refactoring/refactoring.html
    while(v.replace(/^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$/,"")!="")
        v=v.replace(/.$/,"")
    return v
}

function site(v){
    //Esse sem comentarios para que você entenda sozinho ;]
    v=v.replace(/^http:\/\/?/,"")
    dominio=v
    caminho=""
    if(v.indexOf("/")>-1)
        dominio=v.split("/")[0]
        caminho=v.replace(/[^\/]*/,"")
    dominio=dominio.replace(/[^\w\.\+-:@]/g,"")
    caminho=caminho.replace(/[^\w\d\+-@:\?&=%\(\)\.]/g,"")
    caminho=caminho.replace(/([\?&])=/,"$1")
    if(caminho!="")dominio=dominio.replace(/\.+$/,"")
    v="http://"+dominio+caminho
    return v
}
function barra(objeto){
	if (objeto.value.length == 2 || objeto.value.length == 5 ){
	objeto.value = objeto.value+"/";
	}
}
function barraAno(objeto){
	if (objeto.value.length == 4) {
	objeto.value = objeto.value+"/";
	}
}

//MÁSCARA DE MOEDA
//Modo de usar:
//onkeypress="reais(this,event)" onkeydown="backspace(this,event)"
documentall = document.all;

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 && !document.all) {
		//Previne a ação padrão nos navegadores
		if(event.preventDefault){ //standart browsers
			event.preventDefault();
		} else { // internet explorer
			event.returnValue = false;
		}
		var valor = document.getElementById(obj).value;
		var x = valor.substring(0,valor.length-1);
		document.getElementById(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;
	}
//===================================================================================
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 ); }
	}
}

function FormataValor(id,tammax,teclapres) {
	if(window.event) { // Internet Explorer
		var tecla = teclapres.keyCode; }
	else if(teclapres.which) { // Nestcape / firefox
		var tecla = teclapres.which;
	}
	vr = document.getElementById(id).value;
	vr = vr.toString().replace( "/", "" );
	vr = vr.toString().replace( "/", "" );
	vr = vr.toString().replace( ",", "" );
	vr = vr.toString().replace( ".", "" );
	vr = vr.toString().replace( ".", "" );
	vr = vr.toString().replace( ".", "" );
	vr = vr.toString().replace( ".", "" );
	tam = vr.length;

	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<=2)				   { document.getElementById(id).value = 'R$ '+vr; }
		if((tam>5) && (tam<=8))    { document.getElementById(id).value = vr.substr(0,tam-2)+','+vr.substr(tam-2,tam); }
		if((tam>=9) && (tam<=11))  { document.getElementById(id).value = vr.substr(0,tam-5)+'.'+vr.substr(tam-5,3)+','+vr.substr(tam-2,tam); }
		if((tam>=12) && (tam<=14)) { document.getElementById(id).value = vr.substr(0,tam-8)+'.'+vr.substr(tam-8,3)+'.'+vr.substr(tam-5,3)+','+vr.substr(tam-2,tam); }
		if((tam>=15) && (tam<=18)) { document.getElementById(id).value = vr.substr(0,tam-11)+'.'+vr.substr(tam-11,3)+'.'+vr.substr(tam-8,3)+'.'+vr.substr(tam-5,3)+','+vr.substr(tam-2,tam); }
		if((tam>=18) && (tam<=20)) { document.getElementById(id).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); }
	}
}