
// Controlar se esta a decorrer uma pesquisa
var pequisa_activa = false;

// Keyword da ultima pesquisa efectuada
var pesquisa_key = '';
var pesquisa_genero = '';
var pesquisa_estilo = '';
var pesquisa_newkey = '';
var pesquisa_key_time = 0;

// Controlo de timming para pesquisa
var pesquisa_interval = 0;

// Estado da div de resultados
var pesquisa_mostra = false;

// Pesquisar ao fim se algum tempo de escrita...
function musik_pesquisa_interval() {

	// Se a chave é vazia ou já foi pesquisada, terminar
	if(pesquisa_key == pesquisa_newkey && pesquisa_genero == genero_seleccionado && pesquisa_estilo == estilo_seleccionado) {
		window.clearInterval(pesquisa_interval);
		pesquisa_interval = 0;
		if(pesquisa_newkey == '' && pesquisa_genero == '' && pesquisa_estilo == '') {
			document.getElementById('procuramusik').style.visibility = 'hidden';
			pesquisa_mostra = false;
		}
		return;
	}
	
	// Incrementar tempo de pesquisa
	pesquisa_key_time++;
	
	if(pesquisa_key_time >= 10) {
		pesquisa_key_time = 0;
		musik_pesquisa(pesquisa_newkey);
	}
}

// Alteração do texto da pesquisa
function musik_search_update_keyword(new_key) {
	//alert('tv_search_update_keyword('+new_key+')');
	pesquisa_newkey = new_key;
	pesquisa_key_time = 0;
	
	// Se o interval não está activo, activa-lo!!
	if(pesquisa_interval == 0) {
		pesquisa_interval = window.setInterval(musik_pesquisa_interval, 100);
	}
}


// Click no botão de pesquisa
function musik_search_bt_click() {

// Se a janela está aberta, fecha-la
	if((pesquisa_newkey == '' && genero_seleccionado == '' && estilo_seleccionado == '') || pesquisa_mostra) {
		document.getElementById('procuramusik').style.visibility = 'hidden';
		pesquisa_mostra = false;
	}
	// Se a janela está fechada, abri-la e fazer a pesquisa
	else {
		document.getElementById('procuramusik').style.visibility = 'visible';
		pesquisa_mostra = true;
		if(!pequisa_activa && (pesquisa_newkey != pesquisa_key || pesquisa_genero != genero_seleccionado || pesquisa_estilo != estilo_seleccionado))
			musik_pesquisa(pesquisa_newkey);
	}
}

// Efectuar uma nova pesquisa
function musik_pesquisa(key) {
	if(pequisa_activa) {
		return;
	}
	pesquisa_key = key;
	pesquisa_genero = genero_seleccionado;
	pesquisa_estilo = estilo_seleccionado;
	
	if(key == '' && pesquisa_genero == '' && pesquisa_estilo == '') {
		document.getElementById('procuramusik').style.visibility = 'hidden';
		pesquisa_mostra = false;
		return;
	}
	pequisa_activa = true;
	
	
	var req;   
	if( window.XMLHttpRequest ) req = new XMLHttpRequest();
	else if( window.ActiveXObject ) req = new ActiveXObject("Microsoft.XMLHTTP");
	req.open('GET', 'utils/musik_pesquisa.php?keyword='+encodeURIComponent(key)+'&genero='+encodeURIComponent(nomes_generos[genero_seleccionado])+'&estilo='+encodeURIComponent(get_estilo(genero_seleccionado, estilo_seleccionado))+'&'+Math.random(), true);   
	req.onreadystatechange = function (aEvt) {   
	  if (req.readyState == 4) {
		 pequisa_activa = false;
		 if(req.status == 200) {
			 var result_div = document.getElementById('procuramusik');
			 if(!result_div) {
				 alert("Erro ao mostrar resultados de pesquisa! Tente novamente!");
			 } else {
			 	 var html = '<table width="308" border="0" align="center" cellpadding="4" cellspacing="0">';
				 html = html + '<tr><td valign="top">&nbsp;</td><td align="left" valign="top">&nbsp;</td></tr>\n';
				 
				 // Resultado é devolvido no formato:
				 //  0     1           2         3      4       5         6      7
				 // id|url_logo|constituicao|genero|estilo|local_origem|resumo|nome
				 var linhas = req.responseText.split("\n");
				 var tem_resultados = 0;
				 for(var i=0; i<linhas.length; i++) {
					 var colunas = linhas[i].split("|", 8);
					 if(colunas[0] == '') break;
					 // Limitar a 10 resultados, o 10+ mostra um link para ver os restantes resultados noutra página!
					 if(i >= 10) {
						 html = html + '<tr><td>&nbsp;</td><td align="right" class="titulo3"><a href="musik_pesquisa.php?keyword='+encodeURIComponent(key)+'&genero='+encodeURIComponent(nomes_generos[genero_seleccionado])+'&estilo='+encodeURIComponent(get_estilo(genero_seleccionado, estilo_seleccionado))+'" style="margin-right: 5px;">ver todos os resultados</a></td></tr>\n';
						 break;
					 }
					 tem_resultados++;
					 
					 // Imagem Real ou alternativa?
					 var img_path = '';
					 if(colunas[1] != '')
					 	img_path = 'images/'+colunas[1];
					 else
					 	img_path = 'imgs/sem_imagem/sem_logo.jpg';
					 
					 html = html + '<tr><td width="59" valign="top" class="td40"><a href="banda.php?id='+colunas[0]+'"><img src="'+img_path+'" width="47" height="47" border="0" /></a></td>';
					 html = html + '<td width="259" align="left" valign="top" class="td42"><a href="banda.php?id='+colunas[0]+'"><span class="titulo2">'+colunas[7]+'</span></a> ';
					 html = html + '<span class="titulo4">'+colunas[3]+'/'+colunas[4]+'</span><br />\n';
					 html = html + '<span class="titulo3">Constituicao: '+colunas[2]+'</span><br />\n';
					 html = html + '<span class="td41normalfont">&quot;'+colunas[6]+'&quot;<br />\n';
					 html = html + '<a href="banda.php?id='+colunas[0]+'" style="padding-left: 150px;">ver mais </a></span></td>\n';
					 html = html + '</tr><tr><td>&nbsp;</td><td align="left">&nbsp;</td></tr>\n';
				 }
				 
				 // Se não tem resultados, dar essa informação!
				 if(tem_resultados == 0) {
					 html = html + '<tr><td valign="top" align="center" colspan="2" class="verdana12"><strong>A pesquisa não devolveu resultados</strong></td></tr>';
					 result_div.style.height = '70px';
					 window.setTimeout('musik_search_bt_click()', 3050);
				 } else {
					 // Tamanho da caixa, máximo 5 resultados visíveis
					 if(tem_resultados > 3) tem_resultados = 3;
					 var h = 70 + (90 * tem_resultados);
					 result_div.style.height = ''+h+'px';
					 html = html + '<tr><td valign="top" align="center" colspan="2" class="verdana12"><a href="javascript:musik_search_bt_click();">Fechar Janela</a></td></tr>';
				 }

				 html = html + '</table>\n';
				 
				
				 // Mostrar resultados, se não está à vista colocar à vista!!
				 result_div.innerHTML = html;
				 if(!pesquisa_mostra) {
					 result_div.style.visibility = 'visible';
					 pesquisa_mostra = true;
				 }
			 }
		 } else {
		 	alert("Erro na pesquisa! Tente novamente!");
		 }
	  }
	};
	req.send(null);
}