//ABRIR POP-UP MAXIMIZADA
function fullWindow(pagina) {

	largura = screen.width-50;
	altura = screen.height-100;
	fullWindow = window.open(pagina,'_blank','status=1,resizable=yes,scrollbars=yes, width='+largura+', height='+altura+', top=0,left=0');	
}
//VALIDAÇÃO DE CPF
function valida_cpf(campo, numcpf){
	
	document.getElementById("cpf_cnpj_obs").innerHTML = "";
	
	CPF = numcpf;
	
	erro = new String;

	CPF = CPF.replace('.', '');
	CPF = CPF.replace('.', '');
	CPF = CPF.replace('-', '');

	if (CPF == "00000000000" || 
		CPF == "11111111111" || 
		CPF == "22222222222" || 
		CPF == "33333333333" || 
		CPF == "44444444444" || 
		CPF == "55555555555" || 
		CPF == "66666666666" || 
		CPF == "77777777777" || 
		CPF == "88888888888" ||
		CPF == "01234567890" ||
		CPF == "99999999999") {
                            
			erro = "Inválido!"
	}
    
	var a = [];
	var b = new Number;
	var c = 11;

	for (i=0; i<11; i++){
		a[i] = CPF.charAt(i);
		if (i < 9) b += (a[i] * --c);
	}
    
	if ((x = b % 11) < 2) { a[9] = 0 } else { a[9] = 11-x }
	b = 0;
	c = 11;
    
	for (y=0; y<10; y++) b += (a[y] * c--); 
    
	if ((x = b % 11) < 2) { a[10] = 0; } else { a[10] = 11-x; }

	if ((CPF.charAt(9) != a[9]) || (CPF.charAt(10) != a[10])) {
		erro = "Inválido!";
	}

    if (erro.length > 0) {
        //alert(erro);
		document.getElementById("cpf_cnpj_obs").innerHTML = erro;
		campo.value="";
		campo.focus();
        return false;
    }else{
		document.getElementById("cpf_cnpj_obs").innerHTML = "Válido!";
	}
	
}

//VALIDAÇÃO DE CNPJ
function valida_cnpj(campo, numcnpj){
	
	 	CNPJ = numcnpj;
                       
		erro = new String;
		
		CNPJ = CNPJ. replace (".","");
		CNPJ = CNPJ. replace (".","");
		CNPJ = CNPJ. replace ("-","");
		CNPJ = CNPJ. replace ("/","");
		
		if (CNPJ == "00000000000000" || 
			CNPJ == "11111111111111" || 
			CNPJ == "22222222222222" || 
			CNPJ == "33333333333333" || 
			CNPJ == "44444444444444" || 
			CNPJ == "55555555555555" || 
			CNPJ == "66666666666666" || 
			CNPJ == "77777777777777" || 
			CNPJ == "88888888888888" ||
			CNPJ == "01234567890123" ||
			CNPJ == "99999999999999") {
								
				erro = "Inválido!"
		}
		
		if (CNPJ.length < 14) erro = "Inválido";
                
		var nonNumbers = /\D/;
		if (nonNumbers.test(CNPJ)) erro = "Inválido!";
		var a = [];
		var b = new Number;
		var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
		for (i=0; i<12; i++){
			a[i] = CNPJ.charAt(i);
			b += a[i] * c[i+1];
		}
		if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }
		b = 0;
		for (y=0; y<13; y++) {
			b += (a[y] * c[y]);
		}
		if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11-x; }
		if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])){
			erro ="Inválido!";
		}
		document.getElementById("cpf_cnpj_obs").innerHTML = "";
		if (erro.length > 0){
			//alert(erro);
			document.getElementById("cpf_cnpj_obs").innerHTML = erro;
			campo.value="";
			campo.focus();
			return false;
		}else{
			document.getElementById("cpf_cnpj_obs").innerHTML = "Válido!";
		}
}

//Remove caracteres que não seja número
function trimtodigits(tstring){ 
	s=""; 
	ts=new String(tstring); 
	for(x=0;x<ts.length;x++){ 
		ch=ts.charAt(x); 
		if(asc(ch)>=48 && asc(ch)<=57){ 
			s=s+ch; 
		} 
	} 
	return s; 
} 

//MASCARA CNPJ, CPF, DATA, TEL, CEP, EAN13, somente número
function formata(campo,estilo,sonum,e) {
if(estilo == 'cnpj'){
    estilo = '##.###.###/####-##';
}
if(estilo == 'cpf'){
    estilo = '###.###.###-##';
}
if(estilo == 'data'){
    estilo = '##/##/####';
}
if(estilo == 'tel'){
    estilo = '(##)####-####';
}
if(estilo == 'cep'){
    estilo = '#####-###';
}
if(estilo == 'ean13'){
    estilo = '#############';
}
if(estilo == 'num'){
    estilo = '##################################################';
}

if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
if (event.keyCode != 8) {
cnum = false;
for(i=48;i<=57;i++) { if (keycode == i) { cnum = true; } }
//ACEITAR LETRAS ESTÁ COMENTADO
//for(i=96;i<=105;i++) { if (keycode == i) { cnum = true; } }
if (sonum && !cnum) { event.returnValue = false; }
retorno = "";
for(i=0;i<=campo.value.length;i++) {
if (i < estilo.length) {
if (estilo.charAt(i) == '#') { retorno += campo.value.charAt(i); }
else { retorno += estilo.charAt(i); }
}
else { event.returnValue = false; }
}
campo.value = retorno;
}
}
//FIM MASCARA CNPJ
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}
function MM_goToURL() { //v3.0
  var i, args=MM_goToURL.arguments; document.MM_returnValue = false;
  for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
}
function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}
//###################### FUNCAO PARA FAZER A VALIDAÇÃO DE UM CAMPO DE EMAIL  #####################################

function validateEmail(email){
    if (typeof(email) != "string")
	    return false;
    else if (!email.match(/^[A-Za-z0-9]+([_.-][A-Za-z0-9]+)*@[A-Za-z0-9]+([_.-][A-Za-z0-9]+)*\.[A-Za-z0-9]{2,4}$/))
    	return false;
	return true;
}

function checkEmail(obj){
    var message = (validateEmail(obj.value)) ? "Valid!" : "Invalid!";
	document.getElementById("message").innerHTML = message;
}

// Validação de DATA
function ValidarData(campodata,id)
{
//exemplo: campo = document.formulario.data => ValidarData(document.formulario.data)

var valordata = campodata.value;
var strdia   = valordata.substring(0,2);
var strmes   = valordata.substring(3,5);
var strano   = valordata.substring(6,10);
var dia = parseInt(strdia,10);
var mes = parseInt(strmes,10);
var ano = parseInt(strano,10);
var anobissexto;
var bo_valido = true;
var anoatual = new Date();

anoatual = anoatual.getYear();


		if(valordata.length!=10){bo_valido=false;}
		if(isNaN(dia)||isNaN(mes)||isNaN(ano)){bo_valido=false;}
		if((strdia.length!=2)||(strmes.length!=2)||(strano.length!=4)){bo_valido=false;}
		if((ano>2090)||(ano<=1800)){bo_valido=false;}
		if((dia>31)||(dia==0)||(mes>12)||(mes==0)){bo_valido=false;}
		 
		if(ano%4 == 0)
				anobissexto = 1;
			else
				anobissexto = 0;
		if(((mes == 2) && (dia > (28 + parseInt(anobissexto,10)))) || (mes == 4 || mes == 6 || mes == 9 || mes == 11) && (dia > 30)){
			bo_valido=false;
		}
 
		if(!bo_valido)
		{
		  //alert("Data Inválida!");
		  document.getElementById(id).innerHTML="";
		  document.getElementById(id).innerHTML="Data inválida";
		  campodata.value="";
		  campodata.style.backgroundColor="#00FF00";
		  campodata.style.color="#000000";
		  //campodata.focus();
		  return false;
		}
		else
		{
		  document.getElementById(id).innerHTML="";
		  document.getElementById(id).innerHTML="Data válida";
		  campodata.style.backgroundColor="#FFECC6";
		  campodata.style.color="#666666";
		  return true;
		}
}
//###################### FIM - FUNCAO PARA FAZER A VALIDAÇÃO DE UM CAMPO DE EMAIL  #####################################
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 && !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;

}

<!--
//*******************************************************
// Script para procura interna dentro de um combobox
//
// Desenvolvido por Fabricio Nogueira Magri
// 20/09/2005
// Contato: fabricio.magri@bol.com.br
// Versão: 1.1
//
// Atualizações:
// 25/05/2006 -> Corrigido falha na busca ao digitar
//               caracteres maiúsculos.
//*******************************************************

var _str = "";
var _timeout = 0;

function cbboxSearch(sel, e) {
    var i=0, c=true;
    _str = _str + String.fromCharCode(e.keyCode);
    _str = _str.toLowerCase();
    while (c) {
        var textOpt = sel.options[i].text.toLowerCase();
        var strOpt = textOpt.substr(0, (_str.length));
        if (strOpt == _str) {
            sel.options[i].selected = true;
            c = false;
        }
        if (i >= (sel.options.length - 1)) {
            c = false;
        }
        i++;
    }
    clearTimeout(_timeout);
    _timeout = setTimeout("cbboxSearchRestart()", 2000);
}

function cbboxSearchRestart() {
    clearTimeout(_timeout);
    _str = "";
}
//-->

