function ajaxAddMusica(id_musica, id)
{
	if (ById(id).checked == true){
		tipo = 'gravar';
	}else{
		tipo = 'remover';
	}
	
	$.post("grava_sessao.php",
	{
		id: id_musica,
		tipo: tipo,
		acao:'exibir_principal'
	},function(xml)
	{
		//ById('confirma').style.display = '';	
	});  	
}

function ajaxAddMusicaTB(id_musica, id)
{
	if (ById(id).checked == true){
		tipo = 'gravar';
	}else{
		tipo = 'remover';
	}
	
	$.post("grava_sessao.php",
	{
		id: id_musica,
		tipo: tipo,
		acao:'exibir_principal_tb'
	},function(xml)
	{
		//ById('confirma').style.display = '';	
	});  	
}

function ajaxEnviarSenha()
{
	$.post("/ajax.php",
	{
		email: ById('email_senha').value,
		acao:'ajaxEnviarSenha'
	},function(xml)
	{
		ById('esqueci_senha').style.display = 'none';
		ById('td_email').innerHTML = "<br />" + xml;
		ById('esqueci_senha_resposta').style.display = 'block';
	});  	
}

function ajaxAtualizaNumeroClick(id_publicidade){
	$.post("ajax.php",
	{
		id_publicidade: id_publicidade,
		acao:'AtualizaNumeroClick'
	},function(xml)
	{
		
	});  
}

function ajaxBuscarCNPJ(cnpj)
{
	$.post("ajax.php",
	{
		cnpj: cnpj,
		acao:'ajaxBuscarCNPJ'
	},function(xml)
	{
		if (xml != 0) {
			clickElement('link_login');
			//ById('link_login').onclick();
			//window.location = "http://edig.servehttp.com:81/~trevodigital/cadastro_artista.php?acao=exibirForm2selo#TB_inline?a=10&height=200&width=450&inlineId=loginSeloGravadora&modal=true";
		}
	});  
}

function clickElement(elementid){
    var e = document.getElementById(elementid);
    if (typeof e == 'object') {
        /*if(typeof e.click != 'undefined') {
            e.click();
            alert('click');
            return false;
        }
        else */
        if(document.createEvent) {
            var evObj = document.createEvent('MouseEvents');
            evObj.initEvent('click',true,true);
            e.dispatchEvent(evObj);
            //alert('createEvent');
            return false;
        }
        else if(document.createEventObject) {
            e.fireEvent('onclick');
            //alert('createEventObject');
            return false;
        }
        else {
            e.click();
            alert('click');
            return false;
        }
    }
}

function atualizarEntrevista(id_artista)
{
	if (id_artista != ""){
		$.post("index.php",
		{
			id_artista: id_artista,
			acao:'ajaxAtualizaEntrevista'
		},function(xml)
		{
			ById('conteudo_entrevista').innerHTML = xml;
		});  
	}
}

function ajaxBuscarBonus(chave)
{
	$.post("ajax.php",
	{
		chave: chave,
		acao:'ajaxBuscarBonus'
	},function(xml)
	{
		if (xml != 0) {
			ById('bonus_alert').innerHTML = "Chave de bonus válida - R$ 10,00";
		}else{
			ById('bonus_alert').innerHTML = "Chave de bonus inválida";
		}
	});  
}

function ajaxBuscarPasseLivre(chave)
{
	$.post("ajax.php",
	{
		chave: chave,
		acao:'ajaxBuscarPasseLivre'
	},function(xml)
	{
		alert(xml);
		if (xml != 0) {
			ById('passe_alert').innerHTML = "Passe livre válido!";
		}else{
			ById('passe_alert').innerHTML = "Passe livre inválida";
		}
	});  
}

function ajaxBuscarCEP(cep)
{
	ById('endereco').value = 'aguarde...';
	ById('cidade').value = 'aguarde...';
	$.post("ajax.php",
	{
		cep: cep,
		acao:'ajaxBuscarCEP'
	},function(xml)
	{
		ById('numero').focus();
		frase = xml;
		var res = frase.split("|");
		res[2] = res[2].replace("\n","");
		res[2] = res[2].replace("\r","");
		ById('endereco').value = trim(res[0]);
		ById('cidade').value = trim(res[1]);
		ById('estado').value = trim(res[2]);
	});  
}


function trim(str){
    if(str.length < 1)
      return "";
    str = RTrim(str);
    str = LTrim(str);    

    if(str == "")
      return "";
    else
      return str;
  }

  function RTrim(str){
    var espaco = String.fromCharCode(32);
    var tamanho = str.length;
    var temp = "";
    if(tamanho < 0)
      return "";
  
    var temp2 = tamanho - 1;
    while(temp2 > -1){
      if(str.charAt(temp2) == espaco){
        // não faz nada
      }
      else{
        temp = str.substring(0, temp2 + 1);
        break;
      }
      temp2--;
    }
    return temp;
  }
   
  function LTrim(str){
    var espaco = String.fromCharCode(32);
    var tamanho = str.length;
    var temp = "";
    if(tamanho < 0)
      return "";

    var temp2 = 0;

    while(temp2 < tamanho){
      if(str.charAt(temp2) == espaco){
        // não faz nada
      }
      else{
        temp = str.substring(temp2, tamanho);
        break;
      }
      temp2++;
    }
    return temp;
  }

/*
function processarXMLCEP(obj){
	var dataArray   = obj.getElementsByTagName("endereco");
	if(dataArray.length > 0) {
		//percorre o arquivo XML paara extrair os dados
		for(var i = 0 ; i < dataArray.length ; i++) {
			var item = dataArray[i];
			//contéudo dos campos no arquivo XML
			if(item.getElementsByTagName("logradouro").item(0).firstChild) 
				ById('endereco').value = item.getElementsByTagName("logradouro").item(0).firstChild.nodeValue;
		}
	} else {
		//caso o XML volte vazio, printa a mensagem abaixo
		alert ( 'Não consegui localizar os dados deste cliente.' );
	}
}
*/
function ajaxBuscarLoginSelo(){
	$.post("ajax.php",
	{
		login: ById('login').value,
		senha: ById('senha_login').value,
		cnpj: ById('cnpj').value,
		acao:'ajaxBuscarLoginSelo'
	},function(xml)
	{
		if (xml == 0) {
			ById('id_selo').value = 0;
			ById('loginIncorreto').innerHTML = "<span class='fonte_11px_laranja'>DADOS INCORRETOS!</span>";
		}else{
			ById('id_selo').value = xml;
			ById('nome_artista').focus();
			
			ById('loginSeloGravadora').style.display = 'none';
			ById('btn_artista_dif').style.display = 'block';
			ById('btn_artista').style.display = 'none';
			
			ById('cnpj').readOnly = true;
			
			ById('nome_responsavel').disabled = true;
			ById('nome_responsavel').value = 'preenchido';
			
			ById('numero').disabled = true;
			ById('numero').value = 'preenchido';
			
			ById('nome_empresa').disabled = true;
			ById('nome_empresa').value = 'preenchido';
			
			ById('inscricao_estadual').disabled = true;
			ById('inscricao_estadual').value = 'preenchido';
			
			ById('inscricao_municipal').disabled = true;
			ById('inscricao_municipal').value = 'preenchido';
			
			ById('telefone').disabled = true;
			
			ById('endereco').disabled = true;
			ById('endereco').value = 'preenchido';
			
			ById('complemento').disabled = true;
			ById('complemento').value = 'preenchido';
			
			ById('cidade').disabled = true;
			ById('cidade').value = 'preenchido';
			
			ById('estado').disabled = true;
			
			ById('cep').disabled = true;
			/*
			ById('endereco_corresp').disabled = true;
			ById('cidade_corresp').disabled = true;
			ById('estado_corresp').disabled = true;
			ById('cep_corresp').disabled = true;
			*/
			ById('corresp').disabled = true;
			tb_remove();
			ById('nome_td_artista').innerHTML = "Nome do Artista ou banda: <span class='fonte_11px_vermelha'>* </span>";
			
		}
	});  
	
	
}
	
/* FUNÇÃO RESPONSÁVEL POR VERIFICAR SE JÁ EXISTE ESTE E-MAIL CADASTRADO NA BASE DE DADOS */
function ajaxVerificarEmail(){
	$.post("ajax.php",
	{
		email: ById('email').value,
		acao:'ajaxVerificarEmail'
	},function(xml)
	{
		if (xml != 0)
		{
			ById('email_alert').innerHTML = "E-mail cadastrado para outro ouvinte/artista.";						
			ById('email').value = "";
			ById('email').focus();
		}else{
			ById('email_alert').innerHTML = "";						
		}
	});  
}

/* FUNÇÃO RESPONSÁVEL POR VERIFICAR SE JÁ EXISTE ESTE DIRETÓRIO CADASTRADO NA BASE DE DADOS */
function ajaxVerificarDiretorio(){
	$.post("ajax.php",
	{
		diretorio: ById('diretorio').value,
		acao:'ajaxVerificarDiretorio'
	},function(xml)
	{
		if (xml == 1)
		{
			ById('diretorio_alert').innerHTML = "Diretório cadastrado para outro artista.";						
			ById('diretorio').value = "";
			ById('diretorio').focus();
		}
		if (xml == 2)
		{
			ById('diretorio_alert').innerHTML = "URL inválida, por favor escolha novamente.";						
			ById('diretorio').value = "";
			ById('diretorio').focus();
		}
		
		if (xml == 0)
		{
			ById('diretorio_alert').innerHTML = "";						
		}
	});  
}

function ajaxValidarCNPJ(cnpj)
{
	$.post("ajax.php",
	{
		cnpj: cnpj,
		acao:'ajaxValidarCNPJ'
	},function(xml)
	{
		if (xml == 0){
			ById('cnpj_alert').innerHTML = "CNPJ Inválido.";
			ById('cnpj').value = "";
			ById('cnpj').focus();
		}else{
			ajaxBuscarCNPJ(cnpj);
			ById('cnpj_alert').innerHTML = "";
		}
	});  
}

function ajaxValidarCPF(cpf, id)
{
	if (id == ""){
		id = "cpf_alert";
	}
	$.post("ajax.php",
	{
		cpf: cpf,
		acao:'ajaxValidarCPF'
	},function(xml)
	{
		if (xml == 0){
			ById(id).innerHTML = "CPF Inválido.";
			$("#cpf").val();
			ById('cpf').focus();
			return false;
		}else{
			ById(id).innerHTML = "";
			return true;
		}
	});  
}

function ajaxVerificarTitularConta(nome)
{
	$.post("ajax.php",
	{
		nome: nome,
		acao:'ajaxVerificarTitularConta'
	},function(xml)
	{
		if (xml == 0){
			ById('info_alert').innerHTML = "Títular deve ser o mesmo do responsável pela banda.";
			ById('info_alert').innerHTML = "";
			ById('titular_conta').focus();
			ById('titular_conta').value = "";
			return false;
		}else{
			ById('info_alert').innerHTML = "";
			return true;
		}
	});  
	
}
function countNaFaixa(id)
{
	if(id!="")
	{
		var id_musica = $("#id_musica").val();
		if(id_musica==undefined){id_musica=0;}
		$.post("ajax.php", {id: id, id_m: id_musica, acao:'countNafaixa'}, function(r){
			if(r==-1)
			{
				$("#promo").attr("disabled", "disabled");
				$("#promo_total").html("Seu limite de músicas grátis por obra foi ultrapassado!");
				$("#valor_faixa").show();
				$("#vlr_gratis").hide();
			}
			else if(r==-2)
			{
				$("#promo").attr("disabled", "disabled");
				$("#promo_total").html("Favor checar a validade de sua anuidade para selecionar esta opção!");
				$("#valor_faixa").show();
				$("#vlr_gratis").hide();
			}
			else
			{
				$("#promo_total").html("Músicas grátis disponíveis: "+r);
				$("#promo").removeAttr("disabled");
				$("#valor_faixa").hide();
				$("#vlr_gratis").show();
			}
			if($("#promo").attr("checked"))
			{
				$("#valor_faixa").hide();
				$("#vlr_gratis").show();
			}
			else
			{
				$("#valor_faixa").show();
				$("#vlr_gratis").hide();
			}
		});
	}
}
function checkNaFaixa()
{
	id = ById('id_album').value;
	if(id!='')
	{
		countNaFaixa(id);
	}
	if($("#promo").attr("checked"))
	{
		$("#valor_faixa").hide();
		$("#vlr_gratis").show();
	}
	else
	{
		$("#valor_faixa").show();
		$("#vlr_gratis").hide();
	}
}