// JavaScript Document

function CreateControl(DivID, CLSID, ObjectID, WIDTH, HEIGHT, URL, AUTOSTART)
{
  var d = document.getElementById(DivID);
  d.innerHTML = 
    '<object classid=' + CLSID + ' id=' + ObjectID + ' width=' + WIDTH + ' height=' + HEIGHT +'><param name="URL" value=' + URL + '><param name="autoStart" value=' + AUTOSTART + '/>';
}





try{
    xmlhttp = new XMLHttpRequest();
}catch(ee){
    try{
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    }catch(e){
        try{
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }catch(E){
            xmlhttp = false;
        }
    }
}

function doBusca(tuf,tipo){

    //limpa o select
    var c=document.getElementById("temas")
    while(c.options.length>0)c.options[0]=null
    c.options[0]=new Option(" -- Aguarde ... -- "," -- Aguarde ... -- ")

    //Monta a url com a uf
    xmlhttp.open("GET", "ajax_edicoes.asp?ed="+tuf+"&tipo="+tipo,true);

    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4){
            //limpa o select
            var c=document.getElementById("temas")
            while(c.options.length>0)c.options[0]=null
            //Transforma a lista de cidades ASP em Javascript

           var atemas=eval(xmlhttp.responseText)
			//var atemas= xmlhttp.responseText
	
            //popula o select com a lista de cidades obtida
			var temas;
            for(var i=0;i<atemas.length;i++){
				temas = atemas[i];
				temas = temas.replace(/\+/g," ");
	                temas=unescape(temas)
                c.options[c.options.length]=new Option(temas,temas)
            }
        }
    }

    xmlhttp.send(null)
}

function buscar() {
	
	var tamanho_pesquisa = new String()
		tamanho_pesquisa = document.form.b.value;
	
	if(tamanho_pesquisa.length < 2)
	{
	
		alert('ATENÇÃO: Sua busca deve conter no mínimo dois caracteres!');
		document.form.b.select();
		document.form.b.focus();

	}else{
	
	window.opener.location  = 'busca.asp?b=' +document.form.b.value+ '&tipo=' +document.form.tipo.value+ '&t=' +document.form.temas.value+ '&dt=' + document.form.dataatual.value+'';
    window.close();
	}

}
function novabusca() {
	
	var tamanho_pesquisa = new String()
		tamanho_pesquisa = document.form.b.value;
	
	if(tamanho_pesquisa.length < 2)
	{
	
		alert('ATENÇÃO: Sua busca deve conter no mínimo dois caracteres!');
		document.form.b.select();
		document.form.b.focus();

	}else{
	
	window.location  = 'busca.asp?b=' +document.form.b.value+ '&tipo=' +document.form.tipo.value+ '&t=' +document.form.temas.value+ '&dt=' + document.form.dataatual.value+'';

	}

}

function select_drop(sel_name, abbr_name)
{
	if(abbr_name!=''){
		if(sel_name.length > 0){
			var maxIndex = sel_name.length;
				for(var i=0; i<maxIndex; i++){
					if(abbr_name== sel_name.options[i].value){
						sel_name.selectedIndex = i;
						break;
					}
				}
			}
		}
	return true;    
}




function IrAoCorreio()
{
  open('http://www.correios.com.br/servicos/cep/cep_default.cfm','IrAoCorreio','location=no,resize=no, width=730,height=400,left=18,top=18,maximized=0,scrollbars=1');
}

/************************************************
* function verificaDataform
* Verifica se um campo data é válido.
* Input: Campo do formulário que contém a data
* Esta função pega o campo diretamente, pois assim
* pode dar uma resposta melhor ao usuário.
*************************************************/

function verificaDataform(data){
	var Date = new String(data);
	Day = "";
	Month = "";
	Year = "";
	i =  0;
	for (i=0;(i<Date.length) && (Date.charAt(i) != '/');i++)
		Day = Day + Date.charAt(i);
	i++;
	for (;(i<Date.length) && (Date.charAt(i) != '/');i++)
		Month = Month + Date.charAt(i);
	i++;
	for (;(i<Date.length);i++)
		Year = Year + Date.charAt(i);
	for(i=0;i<Date.length;i++){
		NroAsc = asc(Date.substring(i,i+1))
		if (!(NroAsc>=48 && NroAsc<=57) || !(NroAsc = 47) )  {
			return false;
		}
	}
	if(!isNumeric(Month)) {
		return false;
	}
	if (eval(Month) > 12){
		return false;
	}
	if(!isNumeric(Day)) {
		return false;
	}
	if (eval(Day) > 31){
		return false;
	}
	if(!isNumeric(Year)) {
		return false;
	}
	if(eval(Year) < 1900) {
		return false;
	}
	return true;
}


/************************************************
* function verificaCPF
* Verifica se um CPF é válido
* Input: cpf a ser verificado
************************************************/

function verificaCPF(cpf)
{
	var dac = "", inicio = 2, fim = 10, soma, digito, i, j
	for (j=1;j<=2;j++) {
		soma = 0
		for (i=inicio;i<=fim;i++) {
			soma += parseInt(cpf.substring(i-j-1,i-j))*(fim+1+j-i)
		}
		if (j == 2) { soma += 2*digito }
		digito = (10*soma) % 11
		if (digito == 10) { digito = 0 }
		dac += digito
		inicio = 3
		fim = 11
	}
	return (dac == cpf.substring(cpf.length-2,cpf.length))
}

/************************************************
* function verificaCGC
* Verifica se um CGC é válido
* Input: cgc a ser verificado
************************************************/

function verificaCGC(scgc) {
	cgc = trimtodigits(scgc);
	if ((cgc.indexOf("-") != -1) || (cgc.indexOf(".") != -1) || (cgc.indexOf("/") != -1)){
		return( false )
	}
	var df, resto, dac = ""
	df = 5*cgc.charAt(0)+4*cgc.charAt(1)+3*cgc.charAt(2)+2*cgc.charAt(3)+9*cgc.charAt(4)+8*cgc.charAt(5)+7*cgc.charAt(6)+6*cgc.charAt(7)+5*cgc.charAt(8)+4*cgc.charAt(9)+3*cgc.charAt(10)+2*cgc.charAt(11)
	resto = df % 11
	dac += ( (resto <= 1) ? 0 : (11-resto) )
	df = 6*cgc.charAt(0)+5*cgc.charAt(1)+4*cgc.charAt(2)+3*cgc.charAt(3)+2*cgc.charAt(4)+9*cgc.charAt(5)+8*cgc.charAt(6)+7*cgc.charAt(7)+6*cgc.charAt(8)+5*cgc.charAt(9)+4*cgc.charAt(10)+3*cgc.charAt(11)+2*parseInt(dac)
	resto = df % 11
	dac += ( (resto <= 1) ? 0 : (11-resto) )
	return (dac == cgc.substring(cgc.length-2,cgc.length))
}

/************************************************
* function verificaEmail
* Verifica se um email é válido
* Input: email a ser verificado
************************************************/

function verificaEmail(email) {
	var s = new String(email);
	// { } ( ) < > [ ] | \ /
	if ((s.indexOf("{")>=0) || (s.indexOf("}")>=0) || (s.indexOf("(")>=0) || (s.indexOf(")")>=0) || (s.indexOf("<")>=0) || (s.indexOf(">")>=0) || (s.indexOf("[")>=0) || (s.indexOf("]")>=0) || (s.indexOf("|")>=0) || (s.indexOf("\"")>=0) || (s.indexOf("/")>=0) )
		return false;
	if (vogalAcentuada(email))
		return false;
	// & * $ % ? ! ^ ~ ` ' "
	if ((s.indexOf("&")>=0) || (s.indexOf("*")>=0) || (s.indexOf("$")>=0) || (s.indexOf("%")>=0) || (s.indexOf("?")>=0) || (s.indexOf("!")>=0) || (s.indexOf("^")>=0) || (s.indexOf("~")>=0) || (s.indexOf("`")>=0) || (s.indexOf("'")>=0) )
		return false;
	// , ; : = #
	if ((s.indexOf(",")>=0) || (s.indexOf(";")>=0) || (s.indexOf(":")>=0) || (s.indexOf("=")>=0) || (s.indexOf("#")>=0) )
		return false;
	// procura se existe apenas um @
	if ( (s.indexOf("@") < 0) || (s.indexOf("@") != s.lastIndexOf("@")) )
		return false;
	// verifica se tem pelo menos um ponto após o @
	if (s.lastIndexOf(".") < s.indexOf("@"))
		return false;
	return true;
}

/************************************************
* function verificaCEP
* Verifica se o CEP está no formato correto
* Input: CEP a ser verificado
************************************************/

function verificaCEP (cep) {
	s = new String(cep);
	if ((s.length > 9) || (s.length < 5))
		return false;
	if (!isInteger(cep))
		return false;
	return true;
}

/************************************************
* function isInteger
* Verifica se um campo é inteiro, inclui dígitos de 0 a 9, vírgula, ponto, espaços e -
* Input: campo a ser verificado
************************************************/

function isInteger(s){
	var i;
	if (isEmpty(s)) 
		return false;
	for (i = 0; i < s.length; i++)
	{   
		var c = s.charAt(i);
		if (!isNumber(c)) return false;
	}
	return true;
}

/************************************************
* function isNumeric
* Verifica se um campo é numérico. Se contém apenas dígitos de 0 a 9
* Input: campo a ser verificado
************************************************/

function isNumeric(s){
	var i;
	if (isEmpty(s)) 
		return false;
	for (i = 0; i < s.length; i++)
	{   
		var c = s.charAt(i);
		if (!isDigit(c)) return false;
	}
	return true;
}

/************************************************
* function warnInvalid
* Gera um alert para o usuário e volta o foco para
* o campo que está com problema
* Input: theField - campo do formulário com problema
*        warnText - texto a ser mostrado no alert
************************************************/

function warnInvalid (theField, warnText)
{   theField.focus()
	theField.select()
	alert(warnText)
	return false
}

// Verifica se o caracter é um dígito de 0 a 9
function isDigit (c)
{ return ((c >= "0") && (c <= "9")) }

// Verifica se uma string tem vogais acentuadas
function vogalAcentuada(s) {
	ls = s.toLowerCase();
	if ((ls.indexOf("á")>=0) || (ls.indexOf("à")>=0) || (ls.indexOf("ã")>=0) || (ls.indexOf("â")>=0) || (ls.indexOf("é")>=0) || (ls.indexOf("í")>=0) || (ls.indexOf("ó")>=0) || (ls.indexOf("õ")>=0) || (ls.indexOf("ô")>=0) || (ls.indexOf("ú")>=0) || (ls.indexOf("ü")>=0))
		return true;
}

// Gera uma string com os caracteres básicos na sequência de códigos ASC
function makeCharsetString(){
	var astr
	astr = ' !"#$%&\'()*+,-./0123456789:;<=>?@'
	astr+= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
	astr+= '[\]^_`abcdefghijklmnopqrstuvwxyz'
	astr+= '{|}~'
	return astr
}

// Retorna o código ASC do caracter passada por parâmetro
function asc(achar){
	var n=0;
	var ascstr = makeCharsetString()
	for(i=0;i<ascstr.length;i++){
		if(achar==ascstr.substring(i,i+1)){
			n=i;
			break;
		}
	}
	return n+32
}

//Remove todos os caracteres excetos 0-9
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;
}
/*inicio */


// Retorna o código ASC do caracter passada por parâmetro
function asc(achar){
	var n=0;
	var ascstr = makeCharsetString()
	for(i=0;i<ascstr.length;i++){
		if(achar==ascstr.substring(i,i+1)){
			n=i;
			break;
		}
	}
	return n+32
}
// Gera uma string com os caracteres básicos na sequência de códigos ASC
function makeCharsetString(){
	var astr
	astr = ' !"#$%&\'()*+,-./0123456789:;<=>?@'
	astr+= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
	astr+= '[\]^_`abcdefghijklmnopqrstuvwxyz'
	astr+= '{|}~'
	return astr
}

// Verifica se uma string tem vogais acentuadas
function vogalAcentuada(s) {
	ls = s.toLowerCase();
	if ((ls.indexOf("á")>=0) || (ls.indexOf("à")>=0) || (ls.indexOf("ã")>=0) || (ls.indexOf("â")>=0) || (ls.indexOf("é")>=0) || (ls.indexOf("í")>=0) || (ls.indexOf("ó")>=0) || (ls.indexOf("õ")>=0) || (ls.indexOf("ô")>=0) || (ls.indexOf("ú")>=0) || (ls.indexOf("ü")>=0))
	return true;
}

// Verifica se o caracter pode fazer parte de um número: 0-9 , . ( ) - e espaço
function isNumber (c) { 
	return ((c >= "0") && (c <= "9") || (c=="-") || (c=="(") || (c==")") || (c==" ") || (c==".") || (c==",")) 
}

// Verifica se o caracter é um dígito de 0 a 9
function isDigit (c) { 
	return ((c >= "0") && (c <= "9")) 
}

/************************************************
* function checkField
* Verificação básica de um campo de formulário por "coisas bobas": & < > | \ /
* Input: campo a ser verificado
************************************************/

function checkField(s) {
	if ((s.indexOf("&")>=0) || (s.indexOf("<")>=0) || (s.indexOf(">")>=0) || (s.indexOf("|")>=0) || (s.indexOf("\"")>=0) || (s.indexOf("/")>=0) )
		return false;
	return true;
}

/************************************************
* function isEmpty
* Verifica se um campo está vazio
* Input: campo a ser verificado
************************************************/

function isEmpty(s) {
	return ((s == null) || (s.length == 0));
}


/************************************************
* function warnInvalid
* Gera um alert para o usuário e volta o foco para
* o campo que está com problema
* Input: theField - campo do formulário com problema
*        warnText - texto a ser mostrado no alert
************************************************/

function warnInvalid (theField, warnText)
{   theField.focus()
	theField.select()
	alert(warnText)
	return false
}

/************************************************
* function warnInvalid_SelectBox
* Gera um alert para o usuário e volta o foco para
* o campo que está com problema
* Esta função é específica para ser usada com campos Select, para outros campos, usar a warnInvalid
* Input: theField - campo do formulário com problema
*        warnText - texto a ser mostrado no alert
************************************************/
function warnInvalid_SelectBox (theField, s)
{
	theField.focus();
	alert(s);
	return false;
}

function openCentered(theURL,winName,winWidth,winHeight,features) {
  var w = (screen.width - winWidth)/2;
  var h = (screen.height - winHeight)/2 - 60;
  features = features+',width='+winWidth+',height='+winHeight+',top='+h+',left='+w;
  window.open(theURL,winName,features);
}


// Função de auto-tabulação
// Parâmetros:
// input - o elemento de formulário que está sendo utilizado 
// len - o tamanho do campo antes do tab automático (normalmente o maxlength)
// e - ? Sempre passar event
//
// Forma de utilização no HTML:
// <input onKeyUp="return autoTab(this, 3, event);">
var isNN = (navigator.appName.indexOf("Netscape")!=-1);

function autoTab(input,len, e) {
	var keyCode = (isNN) ? e.which : e.keyCode; 
	var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];

	if(input.value.length >= len && !containsElement(filter,keyCode)) {
		input.value = input.value.slice(0, len);
		input.form[(getIndex(input)+1) % input.form.length].focus();
	}

	function containsElement(arr, ele) {
		var found = false, index = 0;
		while(!found && index < arr.length)
			if(arr[index] == ele)
				found = true;
			else
				index++;
		return found;
	}

	function getIndex(input) {
		var index = -1, i = 0, found = false;
		while (i < input.form.length && index == -1)
			if (input.form[i] == input)index = i;
			else i++;
		return index;
	}
	return true;
}


