function abrirJanela(url, janela, atr) {
	if (atr == 'S') {
		window.open(url,janela,'scrollbars=no,status=no,width=750,height=530,left=20,top=10,resizable=no');
	}	else {
		window.open(url,janela,'');
	}
}

function verificaExtra() {
	if (document.getElementById('pagina_identificao')) {
		elemento = document.getElementById('pagina_identificao');
		
		//Site - Contato
		if (elemento.value == 'site_contato') {
			
			if (document.getElementById('Nome')) {
		  	campo = document.getElementById('Nome');
		  	if (campo.value == '') {
		  		alert('Favor preencher o campo Nome');
		  		campo.focus();
		  		return false;
		  	}
		  }
			
			if (document.getElementById('Email')) {
		  	campo = document.getElementById('Email');
		  	if (campo.value == '') {
		  		alert('Favor preencher o campo E-mail');
		  		campo.focus();
		  		return false;
		  	}
		  }
			
			if (document.getElementById('Assunto')) {
		  	campo = document.getElementById('Assunto');
		  	if (campo.value == '') {
		  		alert('Favor preencher o campo Assunto');
		  		campo.focus();
		  		return false;
		  	}
		  }
			
			if (document.getElementById('Mensagem')) {
		  	campo = document.getElementById('Mensagem');
		  	if (campo.value == '') {
		  		alert('Favor preencher o campo Mensagem');
		  		campo.focus();
		  		return false;
		  	}
		  }	
			
		}
		//Site - Contato
		
		//Site - Orçamento Joomla
		if (elemento.value == 'site_orcamento') {
			
			if (document.getElementById('Nome')) {
		  	campo = document.getElementById('Nome');
		  	if (campo.value == '') {
		  		alert('Favor preencher o campo Nome');
		  		campo.focus();
		  		return false;
		  	}
		  }
			
			if (document.getElementById('Email')) {
		  	campo = document.getElementById('Email');
		  	if (campo.value == '') {
		  		alert('Favor preencher o campo E-mail');
		  		campo.focus();
		  		return false;
		  	}
		  }
			
			if (document.getElementById('Resumo')) {
		  	campo = document.getElementById('Resumo');
		  	if (campo.value == '') {
		  		alert('Favor preencher o campo "Descreva resumidamente o que precisa"');
		  		campo.focus();
		  		return false;
		  	}
		  }	
			
		}
		//Site - Orçamento Joomla
	
	}	
	
	if (document.getElementById('tipo')) {
		campo = document.getElementById('tipo');
		if (campo.value == '' && campo.type != 'hidden') {
			alert('Favor preencher o campo Tipo.');
			campo.focus();
			return false;
		}
	}
	
	if (document.getElementById('nome')) {
		campo = document.getElementById('nome');
		if (campo.value == '') {
			alert('Favor preencher o campo Nome.');
			campo.focus();
			return false;
		}
	}
	
	if (document.getElementById('titulo')) {
		campo = document.getElementById('titulo');
		if (campo.value == '') {
			alert('Favor preencher o campo Título.');
			campo.focus();
			return false;
		}
	}
		
	document.getElementById('formulario1').submit();	
	return true; 
}

function validarER(op, valor, c) {
  if (op == 'data') {
  
    var reg = /^((0[1-9]|[12]\d)\/(0[1-9]|1[0-2])|30\/(0[13-9]|1[0-2])|31\/(0[13578]|1[02]))\/\d{4}$/;  
  
  } else if (op == 'hora') {
    
    var reg = /^([0-1]\d|2[0-3]):[0-5]\d$/;
        
  } else if (op == 'email') {
    
    var reg = /^[\w-]+(\.[\w-]+)*@(([A-Za-z\d][A-Za-z\d-]{0,61}[A-Za-z\d]\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
       
  } else if (op == 'cpf') {

    var cpf = valor;
    var reg = /^\d{3}.\d{3}.\d{3}-\d{2}$/i;
    if(!reg.test(cpf)){
     var invalido = 'sim';
    }
    
    cpf = remove(cpf, ".");
    cpf = remove(cpf, "-");
    
    if (cpf.length != 11 || cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999") {
      var invalido = 'sim';
    }
    
    soma = 0;
    for(i = 0; i < 9; i++)
  	  soma += parseInt(cpf.charAt(i)) * (10 - i);
      resto = 11 - (soma % 11);
      if(resto == 10 || resto == 11)
        resto = 0;
      if(resto != parseInt(cpf.charAt(9))) {
        var invalido = 'sim';
      }
    soma = 0;
    for(i = 0; i < 10; i ++)
      soma += parseInt(cpf.charAt(i)) * (11 - i);
      resto = 11 - (soma % 11);
      if(resto == 10 || resto == 11)
      resto = 0;
      if(resto != parseInt(cpf.charAt(10))){
        var invalido = 'sim';
      } 
        
  }  
  
  if (invalido == 'sim' && valor != '') {
    alert('Valor inválido para este campo.');
    c.value = '';
    c.focus();
  } else {
    if (reg.test(valor) == false && valor != '') {
      alert('Valor inválido para este campo.');
      c.value = '';
      c.focus();
    }
  }
}
 
function mascara(o,f){
v_obj=o
v_fun=f
setTimeout("execmascara()",1)
}

function execmascara(){
v_obj.value=v_fun(v_obj.value)
}


function soLetras(v){
return v.replace(/\d/g,"") //Remove tudo o que não é Letra
}

function soLetrasMA(v){
v=v.toUpperCase() //Maiúsculas
return v.replace(/\d/g,"") //Remove tudo o que não é Letra ->maiusculas
}

function soLetrasMI(v){
v=v.toLowerCase() //Minusculas
return v.replace(/\d/g,"") //Remove tudo o que não é Letra ->minusculas
}

function soNumeros(v){
return v.replace(/\D/g,"") //Remove tudo o que não é dígito
}

function soValorMonetario(v){
v=v.replace(/\D/g,"") //Remove tudo o que não é dígito
v=v.replace(/(\d{1})(\d{1,2})$/,"$1.$2") //Remove tudo o que não é dígito
return v
}

function apenastelefone(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 cpfvalidar(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 cepvalidar(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 cnpjvalidar(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 data(v){
v=v.replace(/\D/g,"") //Remove tudo o que não é dígito
v=v.replace(/(\d{2})(\d)/,"$1/$2") //Coloca um ponto entre o segundo e o terceiro dígitos
v=v.replace(/(\d{2})(\d)/,"$1/$2") //Coloca um ponto entre o quarto e o quinto dígitos
//v=v.replace(/^[0-3]?\d\/[01]?\d\/(\d{2}|\d{4})$/)
v=v.replace(/^((0[1-9]|[12]\d)\-(0[1-9]|1[0-2])|30\-(0[13-9]|1[0-2])|31\-(0[13578]|1[02]))\-\d{4}$/)
//v=v.replace(/^(0[1-9]|[012][0-9]|3[01])/\-(0[1-9]|1[012])/\-([12][0-9]{3})/,"") 
return v
}


//valida formato de hora 00:00 até 23:59 com mascara
//criada em 2008-04-15 15:57
//er=/^(([01][\d])|([2][0-3]))([0-5][\d])/ //ereg que valida a hora(nao usada aqui)
function hora(v){
v=v.replace(/\D/g,"") //Remove tudo o que não é dígito
v=v.replace(/^[^012]/,"") //valida o primeiro dígito #
v=v.replace(/^([2])([^0-3])/,"$1") //valida o segundo dígito ##
v=v.replace(/^([\d]{2})([^0-5])/,"$1")//valida o terceiro dígito ###
v=v.replace(/(\d{2})(\d)/,"$1:$2") //Coloca dois ponto entre o segundo e o terceiro dígitos ##:##
v=v.substr(0,5) //Remove digitos extras (aceita no max 5 caracteres(contando o ':' no meio) )
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 remove(str, sub) {
  i = str.indexOf(sub);
  r = "";
  if (i == -1) return str;
  r += str.substring(0,i) + remove(str.substring(i + sub.length), sub);
  return r;
}

function CheckAll() {
	for (var i=0;i<document.pageform.elements.length;i++) {
		var e = document.pageform.elements[i];
		if (e.type == 'checkbox' && e.name != 'allbox') {
			e.checked = document.pageform.allbox.checked;
		}
	}
}


<!-- Início da Função FormataReais -->
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;

}
//Fim da Função FormataReais -->

var keyTime, keyStr = '', allOpts, lastElement;
var agt = navigator.userAgent.toLowerCase();
//var is_ie = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
var is_gecko = (agt.indexOf("gecko") != -1);
function populate(srcEvent)
{
  var element = (srcEvent)? ((srcEvent.target)? srcEvent.target : srcEvent.srcElement) : window.event.srcElement;
  if(lastElement != element)
  {
    allOpts = new Array();
    for(var i = 0; i < element.options.length; i++)
      allOpts[i] = element.options[i].text.toLowerCase();
    lastElement = element;
  }
}
function setSelection(srcEvent)
{
  var myEvent = (srcEvent)? srcEvent : window.event;
  var element = (myEvent.target)? myEvent.target : myEvent.srcElement;
  var keyCode = myEvent.keyCode;
  // messy JS keycodes force me to preprocess. Note: I use a US keyboard, other keyboards may vary?
  if((keyCode > 47 && keyCode < 58) || (keyCode > 64 && keyCode < 91 || keyCode == 32)) ; // space or alphanumerical characters, leave them alone
  else if(keyCode > 95 && keyCode < 106) keyCode -= 48; // keypad numbers
  else if(keyCode > 105 && keyCode < 112) keyCode -= 64; // keypad '+', '-', '/', '*', '.'
  else if(keyCode > 187 && keyCode < 192) keyCode -= 144; // '/', '.', ',', '-'
  else if(keyCode > 218 && keyCode < 222) keyCode -= 128; // '\', '[', ']'
  else
  {
    switch(keyCode)
    {
      case 187: keyCode = 61; break; // '='
      case 222: keyCode = 39; break; // '''
      case 192: keyCode = 96; break; // '`'
      case 186: keyCode = 59; break; // ';'
      default: return; // do not process non printable characters (unfortunately backspace cannot be supported because browsers like IE interpret backspace as go back a page in history)
    }
  }
  var currentKey = String.fromCharCode(keyCode).toLowerCase();
  var idx, currentSIdx = element.selectedIndex, useOld = false;
  var newTime = new Date().getTime();
  if(keyTime != null && newTime - keyTime < 1500) // do type-ahead if two keys were pressed within 500 milliseconds (0.5 second, one can change this value for customization)
  {
    keyStr += currentKey;
    idx = findIdx();
    if(idx == -1) return; // not found, keep current selection then (leave the incorrect keyStr alone)
  }
  else // unfortunately we seem to have to handle default browser behavior too
  {
    keyStr = currentKey;
    // behavior should be: if next option is available and begins with the same character, select the next option
    // when there is either no more option, or no more option that begins with the same character as the current option,
    // then select the first option that starts with the currentKey
    idx = currentSIdx + 1;
    if(idx >= allOpts.length || allOpts[idx].length == 0 || allOpts[idx].charAt(0) != keyStr)
      idx = findIdx();
  }
  if(idx >= 0) // if keyStr is found in an option, select the option
  {
    element.options[currentSIdx].selected = false;
    // gecko-based browsers have a very strange bug that strikes when user presses
    // the same character multiple times (like 'AAA', 'BBBB'), which could be "fixed"
    // in a strange way too (actually the idx > 0 test is not even necessary!)
    // first make a pattern to check if it's same character multiple times
    var pattern = new RegExp('^' + keyStr.charAt(0) + '+$', "i");
    if(is_gecko && pattern.test(keyStr) && idx > 0) element.options[idx-1].selected = true;
    else element.options[idx].selected = true;
  }
  keyTime = newTime;
}

function findIdx()
{
  // full scan to find the smallest idx that match string keyStr (case-insensitive)
  var len = keyStr.length;
  for(var i = 0; i < allOpts.length; i++)
    if(allOpts[i].length >= len && allOpts[i].substring(0, len) == keyStr)
      return i;
  return -1;
}

function txtBoxFormat(objForm, strField, sMask, evtKeyPress) {

	var i, nCount, sValue, fldLen, mskLen,bolMask, sCod, nTecla;

	if(document.all) { // Internet Explorer
		nTecla = evtKeyPress.keyCode;
	} else if(document.layers) { // Nestcape
		nTecla = evtKeyPress.which;
	} else {
		nTecla = evtKeyPress.which;
		if (nTecla == 8) {
			return true;
		}
	}

	sValue = objForm[strField].value;
	// Limpa todos os caracteres de formatação que
	// já estiverem no campo.
	sValue = sValue.toString().replace( "-", "" );
	sValue = sValue.toString().replace( "-", "" );
	sValue = sValue.toString().replace( ".", "" );
	sValue = sValue.toString().replace( ".", "" );
	sValue = sValue.toString().replace( "/", "" );
	sValue = sValue.toString().replace( "/", "" );
	sValue = sValue.toString().replace( "(", "" );
	sValue = sValue.toString().replace( "(", "" );
	sValue = sValue.toString().replace( ")", "" );
	sValue = sValue.toString().replace( ")", "" );
	sValue = sValue.toString().replace( " ", "" );
	sValue = sValue.toString().replace( " ", "" );
	fldLen = sValue.length;
	mskLen = sMask.length;
	
	i = 0;
	nCount = 0;
	sCod = "";
	mskLen = fldLen;

	while (i <= mskLen) {
		bolMask = ((sMask.charAt(i) == "-") || (sMask.charAt(i) == ":") || (sMask.charAt(i) == ".") || (sMask.charAt(i) == "/"))
		bolMask = bolMask || ((sMask.charAt(i) == "(") || (sMask.charAt(i) == ")") || (sMask.charAt(i) == " "))
		
		if (bolMask) {
			sCod += sMask.charAt(i);
			mskLen++;
		} else {
			sCod += sValue.charAt(nCount);
			nCount++;
		}
		i++;
	}
	
	objForm[strField].value = sCod;
	if (nTecla != 8) { // backspace
		if (sMask.charAt(i-1) == "9") { // apenas números...
			return ((nTecla > 47) && (nTecla < 58)); } // números de 0 a 9
		else { // qualquer caracter...
			return true;
		}
	} else {
		return true;
	}
}
