// JavaScript Document
var xmlHttp
var selector

// function selecionaCanais
function selecionaCanal(id){  
	//document.getElementById("canaisSelecionadosEditar").style.display='none'
	var arraySelecionados = new Array()
	//verifica se existe campo duplicado
	var duplicado = false
	var i=0
	/*$(document).ready(function(){ $("#canaisSelecionados > li:not(:has(ul))").each(
		function(){ 
			if ( $(this).attr("id") == id){
				duplicado = true
			}
		}); 
	});
	if ( duplicado ){
		alert("Canal já selecionado.")
		return false;
	}*/
	
	var duplicadoE = false
	$(document).ready(function(){ $("#canaisSelecionados > li:not(:has(ul))").each( 
		function(){       
			if ( parseInt($(this).attr("id")) == parseInt(id)){
				duplicadoE = true;         
			}else{
				arraySelecionados[i] = $(this).attr("id")
			}			
			i=i+1;
		}); 
	});
	if ( duplicadoE ){
		alert("Canal já selecionado.")
		return false;
	}
	
	xmlHttp=GetXmlHttpObject()
	if (xmlHttp==null)
	{
		alert ("Browser does not support HTTP Request")
		return
	}
	
	var url="selecionaCanal.php"
	url=url+"?q=canal"
	url=url+"&id="+id+"&selecionados="+arraySelecionados
	url=url+"&sid="+Math.random()
	xmlHttp.onreadystatechange=stateChangedcanal
	xmlHttp.open("GET",url,true)
	xmlHttp.send(null)
}

function stateChangedcanal(){ 

	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){ 

		var urlnull="<>"
		//var lis = xmlHttp.responseText.split("+")
		//alert($(lis[0]).attr("id")) 
		document.getElementById("canaisSelecionados").innerHTML+=xmlHttp.responseText
	}
}

function selecionaCanalPorCidadeId(id){
  xmlHttp=GetXmlHttpObject()
	if (xmlHttp==null)
	{
		alert ("Browser does not support HTTP Request")
		return
	}  
  var url="change_canais.php"	
	url=url+"?cidade_id="+id
	url=url+"&sid="+Math.random()  	
	xmlHttp.onreadystatechange=stateCidadeIdCanalId
	xmlHttp.open("GET",url,true)
	xmlHttp.send(null)
}

function stateCidadeIdCanalId(){  
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){ 
    
		var urlnull="<>"
		//var lis = xmlHttp.responseText.split("+")
		//alert($(lis[0]).attr("id"))
		//alert(xmlHttp.responseText);
		var limpo=(document.getElementById("canaisSelecionados").innerHTML=="");		
		if (!limpo) 
      if (confirm('Deseja limpar canais anteriores?')) 
        document.getElementById("canaisSelecionados").innerHTML="";
		selecionaCanal(xmlHttp.responseText);		
	}
}

function selecionaCanalIndividual(id){ 

	//verifica se existe campo duplicado
	var duplicado = false
	$(document).ready(function(){ $("#canaisSelecionados > li:not(:has(ul))").each(
		function(){ 
			if ( $(this).attr("id") == id){
				duplicado = true
			}
		}); 
	});
	if ( duplicado ){
		alert("Canal já selecionado.")
		return false;
	}
	
	var duplicadoE = false
	$(document).ready(function(){ $("#canaisSelecionadosEditar > li:not(:has(ul))").each(
		function(){ 
			if ( $(this).attr("id") == id){
				duplicadoE = true
			}
		}); 
	});
	if ( duplicadoE ){
		alert("Canal já selecionado.")
		return false;
	}

	xmlHttp=GetXmlHttpObject()
	if (xmlHttp==null)
	{
		alert ("Browser does not support HTTP Request")
		return
	}

	var url="selecionaCanal.php"
	url=url+"?q=canalIndividual"
	url=url+"&id="+id
	url=url+"&sid="+Math.random()
	xmlHttp.onreadystatechange=stateChangedcanalIndividual
	xmlHttp.open("GET",url,true)
	xmlHttp.send(null)
}

function stateChangedcanalIndividual(){ 

	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){ 

		var urlnull="<>"
		document.getElementById("canaisSelecionados").innerHTML+=xmlHttp.responseText;
		document.getElementById('bairro').focus();
	}
}



function confirma() {
	if(confirm("Tem certeza que deseja excluir ?")) {
		return true;	
	}
	else {
		return false;
	}
	
}

function carregaDivExpandida(obj){
	Expande2(obj);
}

/**********************/
function ExpandeDados(obj) {
		document.getElementById(obj).style.display="block";
		document.getElementById("div_beneficios").style.display="none";
		document.getElementById("div_categorias").style.display="none";
		document.getElementById("div_palavras").style.display="none";
		document.getElementById("aba").src="img/tit_aba_dados.jpg";
}
function ExpandeBeneficios(obj) {
	document.getElementById(obj).style.display="block";
	document.getElementById("div_dados").style.display="none";
	document.getElementById("div_categorias").style.display="none";
	document.getElementById("div_palavras").style.display="none";
	document.getElementById("aba").src="img/tit_aba_beneficios.jpg";
}

function ExpandeCategorias(obj) {
	document.getElementById(obj).style.display="block";
	document.getElementById("div_dados").style.display="none";
	document.getElementById("div_beneficios").style.display="none";
	document.getElementById("div_palavras").style.display="none";
	document.getElementById("aba").src="img/tit_aba_categorias.jpg";
}
function ExpandePalavras(obj) {
	document.getElementById(obj).style.display="block";
	document.getElementById("div_dados").style.display="none";
	document.getElementById("div_beneficios").style.display="none";
	document.getElementById("div_categorias").style.display="none";
	document.getElementById("aba").src="img/tit_aba_palavras.jpg";
}
/**********************/

function Expande(obj) {
		document.getElementById(obj).style.display="block";
		document.getElementById("teste2").style.display="none";
		document.getElementById("teste3").style.display="none";
		document.getElementById("aba").src="img/tit_aba_dados.jpg";
}
function Expande2(obj) {
	document.getElementById(obj).style.display="block";
	document.getElementById("teste").style.display="none";
	document.getElementById("teste3").style.display="none";
	document.getElementById("aba").src="img/tit_aba_categorias.jpg";
}

function Expande3(obj) {
	document.getElementById(obj).style.display="block";
	document.getElementById("teste").style.display="none";
	document.getElementById("teste2").style.display="none";
	document.getElementById("aba").src="img/tit_aba_palavras.jpg";
}

function Expande4(obj) {
		// se a div clicada eh categoria
	document.getElementById(obj).style.display="block";
	document.getElementById("teste").style.display="none";
	document.getElementById("teste2").style.display="none";
	document.getElementById("teste3").style.display="none";
	document.getElementById("teste5").style.display="none";
	document.getElementById("submit").style.display="none";
	document.getElementById("aba").src="img/tit_aba_produtos.jpg";
	/*document.getElementById(imagem).src = "img/expand.gif";*/
}
function Expande5(obj) {
		// se a div clicada eh categoria
	document.getElementById(obj).style.display="block";
	document.getElementById("teste").style.display="none";
	document.getElementById("teste2").style.display="none";
	document.getElementById("teste3").style.display="none";
	document.getElementById("teste4").style.display="none";
	document.getElementById("submit").style.display="none";
	document.getElementById("aba").src="img/tit_aba_produtos.jpg";
	/*document.getElementById(imagem).src = "img/expand.gif";*/
}

function expandeSub(obj, results) {
	if(document.getElementById(obj).style.display=="none") {
		document.getElementById(obj).style.display="block";
	}
		var cat = "filhos";
		for(i=0;i<results;i++) {
			if(cat+i != obj) {
			document.getElementById(cat+i).style.display="none";
			}
		}
}

function expandeProdutosDados(obj) {
		document.getElementById(obj).style.display="block";
		document.getElementById("teste2").style.display="none";
		document.getElementById("aba").src="img/tit_produto_aba_dados.jpg";
}

function expandeProdutosPalavras(obj) {
		document.getElementById(obj).style.display="block";
		document.getElementById("teste").style.display="none";
		document.getElementById("aba").src="img/tit_produto_aba_palavras.jpg";
}

function mostraEstados() {
	var radioGrp = document.forms[1].atuacao;
	if(radioGrp[1].checked) {
		document.getElementById("estados").style.display="block";
	}
	else if(radioGrp[0].checked) {
		if(confirm("Alterando a área de atuação para nacional, todos os estados serão desmarcados. Deseja continuar?")) {
			document.getElementById("estados").style.display="none";
			for(i=1;i<28;i++) {
				document.getElementById("abc"+i).checked=false;
				
			}
		}
		else {
			document.forms[1].atuacao[1].checked=true;
			document.getElementById("estados").style.display="block";
		}
		
		
	}
}

function verificaAtuacao(atuacao) {
	if(atuacao == "Estadual") {
		alert(atuacao);
		document.getElementById("estados").style.display="block";
	}
}	

function verificaDimensao() {
	document.getElementById('imagem').innerHTML = "<img border=\"0\" src=\""+document.form.imagem.value+"\" name=\"img\" style=\"visibility: hidden\" >"
	alert("teste");
	var largura = document.getElementById("img").width;
	var altura = document.getElementById("img").height;
	alert ("Dimensões: " + largura + " x " + altura);
	return false;
}

function validaFormsugestao(){
	campo = document.form_sugestao;
	nome = trim(campo.nome.value);
	email = trim(campo.email.value);
	assunto = trim(document.form_sugestao.assunto.value);
	mensagem = document.form_sugestao.mensagem.value;
	
	//alert(document.getElementById("assunto").value)
	if(nome == ""){
	  alert("O campo nome não foi preenchido");
	  campo.nome.focus();
	  return false;
	}
	if(email == ""){
		alert("O campo email não foi preenchido");
		campo.email.focus();
		return false;
	}
	parte1 = campo.email.value.indexOf("@");
	tam = campo.email.value.length;
	str  = campo.email.value;
	var antesdoarroba = "";
	var depoisdoarroba = "";
	if (parte1 >= 2)
	{
		for (i=parte1;i<tam;i++)
		{
			depoisdoarroba += str.charAt(i);
		}
		for (i=0;i<parte1;i++)
		{
			antesdoarroba += str.charAt(i);
		}
		if(depoisdoarroba.indexOf(".") > 0)
		{
			if(document.getElementById("assunto").value == "0"){
				alert("O campo Assunto não foi selecionado");
				campo.assunto.focus();
				return false;
			}
			else{
				if(trim(document.getElementById("mensagem").value) == "" || trim(document.getElementById("mensagem").value) == " "){
					alert("O campo Mensagem não foi preenchido");
					campo.mensagem.focus();
					return false;
				}
				else{
					return true;
				}
				return true;
			}
			
			return true;
		}
		else
		{
			alert("O campo " + campo.email.name + " deve ser conter um endereco eletrônico!");
			campo.email.focus();
			return false;
		}
	}
	else
	{
		alert("O campo " + campo.email.name + " deve ser conter um endereco eletrônico!");
		campo.email.focus();
		return false;
	}
	//alert(document.getElementById("assunto").value);
	//~ if(assunto.value == "0"){
		//~ alert("O campo Assunto não foi selecionado");
		//~ campo.assunto.focus();
		//~ return false;
	//~ }
	//~ else{
		//~ return true;
	//~ }
	//~ if(mensagem.value == ""){
		//~ alert("O campo Mensagem não foi preenchido");
		//~ campo.mensagem.focus();
		//~ return false;
	//~ }
	//~ else{
		//~ return true;
	//~ }
}

function expandeSugestao(obj) {
	//alert(obj);
	if(document.getElementById(obj).style.display == "block") {
		//alert("b");
		document.getElementById(obj).style.display = "none";
	}
	else 
	if(document.getElementById(obj).style.display == "none") {
		//alert("a");
		document.getElementById(obj).style.display = "block";
	}
	//alert("c");
	
}
function validaServico(nome_form, nome_campo){ // utilizando em cadastro de serviços de crédito
    campo = document.nome_form;
	if(campo.nome_campo.value == ""){
	   alert("Digite um número válido");
	   campo.nome_campo.focus();
	   return false;
	}
	if(isNaN(campo.nome_campo.value)){
		alert("Somente números por favor");
		campo.nome_campo.focus();
		return false;
	}
	
	else{
		return true;
  }
  
}
// utilizando em cadastro de planos 
function validaCredito(){ 
    campo = document.cadastro;
	if(campo.credito.value == ""){
	   alert("O campo crédito está vazio");
	   campo.credito.focus();
	   return false;
	}
	if(isNaN(campo.credito.value)){
		alert("Somente números por favor");
		campo.credito.focus();
		return false;
	}
	if(campo.nome.value == ""){
	   alert("O campo nome está vazio");
	   campo.nome.focus();
	   return false;
	}
	
	if(campo.valor.value == ""){
	   alert("O campo valor está vazio");
	   campo.valor.focus();
	   return false;
	}
	else{
		return true;
  }
  
}
// utilizando na compra de créditos 
function validaCompra(){
	alert("Atenção! Para comprar créditos é necessário desbloquear os pop-ups do seu navegador.");
	campo = document.credito;
	plano=false;	
	for (i=0;i<campo.plano.length;i++){		
		if (campo.plano[i].checked){
			plano=true;
		}
	}
	if(document.credito.contrato.checked == false){
		alert("Marque a caixa de seleção para aceitar o contrato e efetuar a inclusão.");
		return false;
	}
	if(!plano){
		alert("você deve selecionar um plano");
		return false;
	}
	
	if(campo.dados_bancarios.value == "0"){
		alert("Selecione um sacado");
		return false;		
	}
	if(campo.tipo_pagamento.value == "0"){
		alert("Selecione a forma de pagamento");
		return false;		
	}
	else{
		return true;
	 }
}
function validaCreditoEmpresa(j){
	for(i=0;i<(j+1);i++) {
		if(isNaN(document.getElementById("credito"+i).value)){
		 alert("Digite apenas números");
	   		//campo.credito.focus();
	   		return false;
		}
	}
}

function validarSenha() {
		nome = document.cadastro.nome.value;
		strNome = document.cadastro.nome.value;
		login = document.cadastro.login.value;
		str = document.cadastro.login.value;
		senha = document.cadastro.senha.value;
		senha2 = document.cadastro.senha2.value;
		email = document.cadastro.email.value;
		
		if(nome == "" ) {
			alert("campo nome não preenchido");
			document.cadastro.nome.focus();
			return false;
		}
		if(strNome.length < 2)
		{
			alert("Digite um nome com, no mínimo, 2 caracteres.");
			document.cadastro.nome.focus();
			return false;
		}
		if(email == "") {
			alert("campo email não preenchido");
			document.cadastro.email.focus();
			return false;
		}
		if (!checkMail(email)) {
        	alert("Email inválido");
			document.cadastro.email.focus();
			return false;
		}
		//validar email(verificao de endereco eletronico)
		/*parte1 = document.cadastro.email.value.indexOf("@");
		parte3 = document.cadastro.email.value.length;
		if (!(parte1 >= 1 && parte3 >= 3)) {
			alert("O campo " + document.cadastro.email.name + " deve ser conter um endereco eletronico!");
			document.cadastro.email.focus();
			return false;
		}*/
		if(login == "" ) {
			alert("campo login não preenchido");
			document.cadastro.login.focus();
			return false;
		}
		if(str.length > 20)
		{
			alert("Digite um Login com, no maximo, 20 caracteres.");
			document.cadastro.login.focus();
			return false;
		}
		if(senha == "") {
			alert("campo senha não preenchido");
			document.cadastro.senha.focus();
			return false;
			
		}
		if(senha2 == "") {
			alert("campo confirmar senha não preenchido");
			return false;
			
		}
		if (senha != senha2) {
		   alert("Senhas não batem");
		   return false;
		}
		
		if(document.cadastro.contrato.checked == false){
			alert("Marque a caixa de seleção para aceitar o Termo de Uso e efetuar a inclusão.");
			return false;
		}
}

String.prototype.trim = function()
{
return this.replace(/^\s*/, "").replace(/\s*$/, "");
}


function validaSac() {
	campo = document.cadastro_sac;
	cont = 0;
	if(campo.nome.value.length == 0){
		alert("O campo " + campo.nome.name + " deve ser preenchido!");
		campo.nome.focus();
		return false;
	}
	if(campo.tel1.value != ""){
		cont++;
	}
	if(campo.email.value != ""){
		cont++;
	}
	if(campo.site.value != ""){
		cont++;
	}
	//validar email(verificao de endereco eletronico)
		/*parte1 = campo.email.value.indexOf("@");
		parte3 = campo.email.value.length;
		if (!(parte1 >= 3 && parte3 >= 9)) {
			alert("O campo " + campo.email.name + " deve conter um endereço eletrônico!");
			campo.email.focus();
			return false;
		}*/
	if(cont < 2){
		alert("Você deve preecher pelo menos dois campos além do nome e tel 1!!");
		return false;
		
	}	
	else{
		return true;
	}
	
}
function validaProduto(){
	campo = document.cadastro_produto;	
	if(campo.nome.value == ""){
		alert("Digite um nome por favor");
		return false;
	}
	else if(campo.sub2.value == "-1"){
		alert("Selecione uma categoria por favor");
		return false;
	}
			
	else if(campo.select_sac.value == "0"){
		alert("Selecione um sac por favor");
		return false;
	}
	
	else{
		return true;
	}
}///////////////////////////////////////////////////////////////////////////////////
function isNomeValido(str)
{
	
    var pattern = "abcdefghijklmnopqrstuvxwyzçÇABCDEFGHIJKLMNOPQRSTUVXWYZ0123456789"
    var i = 0;

    do{
        var pos = 0;
        for(var j=0; j<pattern.length; j++)
            if(str.charAt(i) == pattern.charAt(j))
            {
                pos = 1;
                break;
            }
        i++;
    }while(pos == 1 && i < str.length);
    if(pos == 0)
        return false;
    return true;
}
function validaCodigo(){
	campo = document.cadastro_afiliado;
	str = document.cadastro_afiliado.codigo.value;
	valida = isNomeValido(str);
	if(valida == true){
		if(str.length > 2 && document.cadastro_afiliado.contrato.checked == false){
			alert("Marque a caixa de seleção para aceitar o contrato e efetuar a inclusão.");
			campo.codigo.focus();
			return false;
		}
		if(str.length < 2 )
		{
			alert("Digite um código com, no mínimo, 2 dígitos.");
			campo.codigo.focus();
			return false;
		}
		if(isNomeValido(str) == false){
			alert("Digite um nome valido");
			campo.codigo.focus();
			return false;
		}
		
		if(campo.bonus.value == ""){
			alert("Digite um bônus por favor");
			campo.codigo.focus();
			return false;
		}
		else{
			return true;
		}
	
	return true;
	}
	else
	{
		alert("Este campo só aceita caracteres alfanumérios e sem espaços.");
			campo.codigo.focus();
	return false;
	}
} // validaCodigo

// desabilita os campos cpf e cnpj em dados bancários
function desabilitaCampoBancario(){

	if(document.getElementById("pessoa").value == "pf"){
	 	document.getElementById("cpf").disabled = false; 
		document.getElementById("cnpj").disabled = true; 
		document.getElementById("cnpj").style.background = "#CBCBCB";
		document.getElementById("cpf").style.background = "#FFFFFF";
	}
	else if(document.getElementById("pessoa").value == "pj"){
		document.getElementById("cnpj").disabled = false; 
		document.getElementById("cpf").disabled = true; 
		document.getElementById("cpf").style.background = "#CBCBCB";
		document.getElementById("cnpj").style.background = "#FFFFFF";
	}
	if(document.getElementById("pessoa").value == "0"){
		document.getElementById("cpf").disabled = true;
		document.getElementById("cpf").style.background = "#CBCBCB";
		document.getElementById("cnpj").disabled = true;
		document.getElementById("cnpj").style.background = "#CBCBCB";
	}	
}
// valida os campos em dados bancários
function validaBancario(){
	campo = document.cadastro_bancario;
	if(campo.nome_sacado.value == ""){
		alert("Digite o nome do sacado");
		campo.nome_sacado.focus();
		return false;
	}
	if(campo.pessoa.value == "0"){
		alert("Selecione o tipo de pessoa");
		campo.pessoa.focus();
		return false;
	}
	if(campo.cpf.disabled == false){
     
     valida = validaCPF();	
		if(valida == false){
		
			return false;
		}	
	}

	if(campo.cnpj.disabled == false){
	
		valida = validaCNPJ();
		
		if(valida == false){
		
			return false;
		}		
	}
	if(campo.nome_sacado.value == ""){
		alert("Digite o nome do sacado");
		campo.nome_sacado.focus();
		return false;
	}
	if(campo.banco.value == ""){
		alert("Digite o nome do banco");
		campo.banco.focus();
		return false;
	}
	if(campo.agencia.value == ""){
		alert("Digite a agência");
		campo.agencia.focus();
		return false;
	}
	if(campo.conta.value == ""){
		alert("Digite o número da conta");
		campo.conta.focus();
		return false;
	}
	if(campo.endereco.value == ""){
		alert("Digite um endereço");
		campo.endereco.focus();
		return false;
	}
	if(campo.bairro.value == ""){
		alert("Digite um bairro");
		campo.bairro.focus();
		return false;
	}
	if(campo.cidade.value == ""){
		alert("Digite uma cidade");
		campo.cidade.focus();
		return false;
	}
	if(campo.estado.value == ""){
		alert("Digite o código do estado");
		campo.estado.focus();
		return false;
	}
	if(campo.cep.value == ""){
		alert("Digite um cep");
		campo.cep.focus();
		return false;
	}
	exp = /^[1-9]{2}\d{3}\-\d{3}/
    if(!exp.test(campo.cep.value)){
        alert('Numero de Cep Invalido!');
		campo.cep.focus();
		return false;
	}
	
	else{
		return true;
	}	

}

function validaCPF(){
   var cpf = document.cadastro_bancario.cpf.value;
   var filtro = /^\d{3}.\d{3}.\d{3}-\d{2}$/i;
   if(!filtro.test(cpf)){
     window.alert("CPF inválido. Tente novamente.");
	 return false;
   }
   
   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"){
	  window.alert("CPF inválido. Tente novamente.");
	  return false;
   }

   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))){
	 window.alert("CPF inválido. Tente novamente.");
	 return false;
   }
   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))){
     window.alert("CPF inválido. Tente novamente.");
	 return false;
   }
   return true;
 }
 
 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 validaCNPJ() {
CNPJ = document.cadastro_bancario.cnpj.value;
erro = new String;
if (CNPJ.length < 18) erro += "É necessario preencher corretamente o número do CNPJ! \n\n";
if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")){
if (erro.length == 0) erro += "É necessário preencher corretamente o número do CNPJ! \n\n";
}
//substituir os caracteres que não são números
if(document.layers && parseInt(navigator.appVersion) == 4){
x = CNPJ.substring(0,2);
x += CNPJ. substring (3,6);
x += CNPJ. substring (7,10);
x += CNPJ. substring (11,15);
x += CNPJ. substring (16,18);
CNPJ = x;
} else {
CNPJ = CNPJ. replace (".","");
CNPJ = CNPJ. replace (".","");
CNPJ = CNPJ. replace ("-","");
CNPJ = CNPJ. replace ("/","");
}
var nonNumbers = /\D/;
if (nonNumbers.test(CNPJ)) erro += "A verificação de CNPJ suporta apenas números! \n\n";
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 +="Dígito verificador com problema!";
}
 if (erro.length > 0){
alert(erro);
return false;
} else {
return true;
}
}

/////// 
function mascaraDataFiltro(obj,valor){
	//alert(data)
	if (valor.length == 2){
		valor = valor + '/';
		document.getElementById(obj).value = valor;
		return true;              
	}
	if (valor.length == 5){
		valor = valor + '/';
		document.getElementById(obj).value = valor;
		return true;
	}
}
////////
/////// 
function mascaraDataVencimento(){
  var data = document.cadastro_conta.data_vencimento.value;
  if (data.length == 2){
	  data = data + '/';
	document.cadastro_conta.data_vencimento.value = data;
	 return true;              
  }
  if (data.length == 5){
	  data = data + '/';
	 document.cadastro_conta.data_vencimento.value = data;
	  return true;
  }
}
////////
function mascaraDataPagamento(){
	  var data = document.cadastro_conta.data_pagamento.value;
	  if (data.length == 2){
		  data = data + '/';
		document.cadastro_conta.data_pagamento.value = data;
		 return true;              
	  }
	  if (data.length == 5){
		  data = data + '/';
		 document.cadastro_conta.data_pagamento.value = data;
		  return true;
	  }
 }
 function mascaraDataInicioLigueGratis(){
  var data = document.ligue_gratis.inicio_ligue_gratis.value;
  if (data.length == 2){
	  data = data + '/';
	document.ligue_gratis.inicio_ligue_gratis.value = data;
	 return true;              
  }
  if (data.length == 5){
	  data = data + '/';
	 document.ligue_gratis.inicio_ligue_gratis.value = data;
	  return true;
  }
}
function mascaraDataFimLigueGratis(){
  var data = document.ligue_gratis.fim_ligue_gratis.value;
  if (data.length == 2){
	  data = data + '/';
	document.ligue_gratis.fim_ligue_gratis.value = data;
	 return true;              
  }
  if (data.length == 5){
	  data = data + '/';
	 document.ligue_gratis.fim_ligue_gratis.value = data;
	  return true;
  }
}

function mascaraCPF(){
	  var cpf = document.cadastro_bancario.cpf.value;
	  if (cpf.length == 3){
		  cpf = cpf + '.';
		document.cadastro_bancario.cpf.value = cpf;
		 return true;              
	  }
	  if (cpf.length == 7){
		  cpf = cpf + '.';
		 document.cadastro_bancario.cpf.value = cpf;
		  return true;
	  }
	  if (cpf.length == 11){
		  cpf = cpf + '-';
		 document.cadastro_bancario.cpf.value = cpf;
		  return true;
	  }
}
function mascaraCNPJ(){
	  var cnpj = document.cadastro_bancario.cnpj.value;
	  if (cnpj.length == 2){
		  cnpj = cnpj + '.';
		document.cadastro_bancario.cnpj.value = cnpj;
		 return true;              
	  }
	  if (cnpj.length == 6){
		  cnpj = cnpj + '.';
		 document.cadastro_bancario.cnpj.value = cnpj;
		  return true;
	  }
	  if (cnpj.length == 10){
		  cnpj = cnpj + '/';
		 document.cadastro_bancario.cnpj.value = cnpj;
		  return true;
	  }
	  if (cnpj.length == 15){
		  cnpj = cnpj + '-';
		 document.cadastro_bancario.cnpj.value = cnpj;
		  return true;
	  }
 }
 
 function mascaraCNPJEmpresa(){
	  var cnpj = document.form.cnpj.value;
	  if (cnpj.length == 2){
		  cnpj = cnpj + '.';
		document.form.cnpj.value = cnpj;
		 return true;              
	  }
	  if (cnpj.length == 6){
		  cnpj = cnpj + '.';
		 document.form.cnpj.value = cnpj;
		  return true;
	  }
	  if (cnpj.length == 10){
		  cnpj = cnpj + '/';
		 document.form.cnpj.value = cnpj;
		  return true;
	  }
	  if (cnpj.length == 15){
		  cnpj = cnpj + '-';
		 document.form.cnpj.value = cnpj;
		  return true;
	  }
 }        
function mascaraCEP(){
  var cep = document.cadastro_bancario.cep.value;
  if (cep.length == 5){
	  cep = cep + '-';
	document.cadastro_bancario.cep.value = cep;
	 return true;              
  } 
}   

function validaEmpresa() {
	var j = 0;
/*	var gambi = 0;
	var nomedoinput = "gambi"+gambi;*/
	cidade = document.form.cidade.value;
	estado = document.form.estado.value;
	fantasia = document.form.fantasia.value;
	cep = document.form.cep.value;
	for (var i = 0; i < document.form.elements.length; i++) {
		
		if((document.form.elements[i].type == "checkbox")&&(document.form.elements[i].checked == true)){
/*			if (document.form.elements[i].name == String(nomedoinput)){
				if {*/
					j++;
/*				}
				gambi++;
				nomedoinput = "gambi"+gambi;
			}*/
		}
	}
	if (j == 0){
		alert("Nenhuma subcategoria selecionada!");
		return false;
	}
	if(fantasia == "") {
		alert("Campo NOME FANTASIA não preenchido!");
		return false;
	}
	if(cep == "") {
		alert("Campo CEP não preenchido!");
		return false;
	}
	if(estado == 0) {
		alert("Favor selecionar um estado para sua sede.");
		return false;
	}
	if(cidade == "") {
		alert("Favor selecionar uma cidade para sua sede.");
		return false;
	}
	var campo
	var cont = 0
	campo = document.getElementById("canais")
	for (var i = 0; i < campo.length; i++) {
		if(campo[i].selected) {
		//alert(campo[i].value)
		cont++
		}
		
	}
	if(cont==0){
		//alert("Favor escolha pelo menos um canal.");
		//return false
	}
}
                
function handleEnter (field, event) {
	var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
	if (keyCode == 13) {
		var i;
		for (i = 0; i < field.form.elements.length; i++)
			if (field == field.form.elements[i])
				break;
		i = (i + 1) % field.form.elements.length;
		field.form.elements[i].focus();
		return false;
	} 
	else
	return true;
}

function addFav(url,titulo){

	if(url){
		var url   = url;
	}else{
		var url   = "http://www.aquionline.com.br";
	}
	if(titulo){
		var title = titulo;
	}else{
		var title = "AquiOnline.com.br";
	}
    //var url   = "http://www.aquionline.com.br";
    //var title = "AquiOnline.com.br";
    if (window.sidebar) window.sidebar.addPanel(title, url,"");
    else if(window.opera && window.print){
        var mbm = document.createElement('a');
        mbm.setAttribute('rel','sidebar');
        mbm.setAttribute('href',url);
        mbm.setAttribute('title',title);
        mbm.click();
    }
    else if(document.all){window.external.AddFavorite(url, title);}
}
 
 
function LimpaEsseBox(){
	var gambi = 0;
	for (var i = 0; i < document.form.elements.length; i++) {
		if (document.form.elements[i].type == "checkbox") {
				document.getElementById("gambi"+gambi).checked=false;
				gambi++;
		}
	}
	return true;
}

function ValidaCreditos(){
	Creditos = document.cadastro.alocacredito.value;
	
}
function validaFormLigueGratis(){
	campo = document.ligue_gratis;
	if(campo.link_ligue_gratis.value == ""){
		alert("Favor preencher o campo link.");
		campo.link_ligue_gratis.focus();
		return false;
	}
	if(campo.inicio_ligue_gratis.value == ""){
		alert("Favor preencher a data de inicio.");
		campo.inicio_ligue_gratis.focus();
		return false;
	}
		if(campo.inicio_ligue_gratis.value == "00/00/0000"){
			alert("Favor preencher a data de inicio.");
			campo.inicio_ligue_gratis.focus();
			return false;
		}
	
	if(campo.fim_ligue_gratis.value == ""){
		alert("Favor preencher a data fim.");
		campo.fim_ligue_gratis.focus();
		return false;
	}
		if(campo.fim_ligue_gratis.value == "00/00/0000"){
			alert("Favor preencher a data de fim.");
			campo.fim_ligue_gratis.focus();
			return false;
		}
	
	return true;
}

//--->Função para a formatação dos campos...<---
function Mascara(tipo, campo, teclaPress) {
    if (window.event)
    {
        var tecla = teclaPress.keyCode;
    } else {
        tecla = teclaPress.which;
    }

    var s = new String(campo.value);
    // Remove todos os caracteres à seguir: ( ) / - . e espaço, para tratar a string denovo.
    s = s.replace(/(\.|\(|\)|\/|\-| )+/g,'');

    tam = s.length + 1;

    if ( tecla != 9 && tecla != 8 ) {
        switch (tipo)
        {
        case 'CPF' :
            if (tam > 3 && tam < 7)
                campo.value = s.substr(0,3) + '.' + s.substr(3, tam);
            if (tam >= 7 && tam < 10)
                campo.value = s.substr(0,3) + '.' + s.substr(3,3) + '.' + s.substr(6,tam-6);
            if (tam >= 10 && tam < 12)
                campo.value = s.substr(0,3) + '.' + s.substr(3,3) + '.' + s.substr(6,3) + '-' + s.substr(9,tam-9);
        break;

        case 'CNPJ' :

            if (tam > 2 && tam < 6)
                campo.value = s.substr(0,2) + '.' + s.substr(2, tam);
            if (tam >= 6 && tam < 9)
                campo.value = s.substr(0,2) + '.' + s.substr(2,3) + '.' + s.substr(5,tam-5);
            if (tam >= 9 && tam < 13)
                campo.value = s.substr(0,2) + '.' + s.substr(2,3) + '.' + s.substr(5,3) + '/' + s.substr(8,tam-8);
            if (tam >= 13 && tam < 15)
                campo.value = s.substr(0,2) + '.' + s.substr(2,3) + '.' + s.substr(5,3) + '/' + s.substr(8,4)+ '-' + s.substr(12,tam-12);
        break;

        case 'TEL' :
            if (tam > 2 && tam < 4)
                campo.value = '(' + s.substr(0,2) + ') ' + s.substr(2,tam);
            if (tam >= 7 && tam < 11)
                campo.value = '(' + s.substr(0,2) + ') ' + s.substr(2,4) + '-' + s.substr(6,tam-6);
        break;

        case 'DATA' :
            if (tam > 2 && tam < 4)
                campo.value = s.substr(0,2) + '/' + s.substr(2, tam);
            if (tam > 4 && tam < 11)
                campo.value = s.substr(0,2) + '/' + s.substr(2,2) + '/' + s.substr(4,tam-4);
        break;
		
		case 'DATAANO' :
            if (tam > 2 && tam < 4)
                campo.value = s.substr(0,2) + '/' + s.substr(2, tam);
            /*if (tam > 4 && tam < 11)
                campo.value = s.substr(0,2) + '/' + s.substr(2,2) + '/' + s.substr(4,tam-4);*/
        break;
        
        case 'CEP' :
			if (tam > 2 && tam < 4)
                campo.value = s.substr(0,2) + ' ' + s.substr(2, tam);
            if (tam > 5 && tam < 7)
                campo.value = s.substr(0,5) + '-' + s.substr(5, tam);
        break;
	
	case 'HORA' :
            if (tam > 2 && tam < 4)
                campo.value = s.substr(0,2) + ':' + s.substr(2, tam);
            if (tam > 4 && tam < 11)
                campo.value = s.substr(0,2) + ':' + s.substr(2,2) + ':' + s.substr(4,tam-4);
	break;

        }
    }
	
}

//--->Função para verificar se o valor digitado é número...<---
function digitos(event){
    if (window.event) {
        // IE
        key = event.keyCode;
    } else if ( event.which ) {
        // netscape
        key = event.which;
    }
    if ( key != 8 || key != 13 || key < 48 || key > 57 )
        return ( ( ( key > 47 ) && ( key < 58 ) ) || ( key == 8 ) || ( key == 13 ) );
    return true;
}

function checkMail(mail){
	var er = new RegExp(/^[A-Za-z0-9_\-\.]+@[A-Za-z0-9_\-\.]{2,}\.[A-Za-z0-9]{2,}(\.[A-Za-z0-9])?/);
	if(typeof(mail) == "string"){
			if(er.test(mail)){ return true; }
	}else if(typeof(mail) == "object"){
			if(er.test(mail.value)){ 
					return true; 
			}
	}else{
			return false;
	}
}  

function getLinksSubcategoria(idCategoria,url,nome_canal){      
  //$("#subcategorias_rodape").html("<li>Carregando...</li>");
  //$("#subcategorias_rodape").slideUp();
  $.ajax({
    url: url+"getLinksSubcategoria.php",
    data: ({id : idCategoria,nome_canal : nome_canal}),
    type: "POST",
    cache: false,
    success: function(html){
      $("#subcategorias_rodape").html(html);
    }
  });
  //$("#subcategorias_rodape").slideDown();
}

function markLinkCategoria(id){
  obj=$('#'+id);
  pai=obj.parents("ul");
  pai.find("a").css("color","black");
  obj.css("color","#F87817");
  
  
}
