
// Controlar se esta a decorrer uma pesquisa
var pequisa_activa = false;

// Keyword da ultima pesquisa efectuada
var pesquisa_key = '';
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 tv_pesquisa_interval() {
	//alert("tv_pesquisa_interval - "+pesquisa_key_time);
	
	// Se a chave é vazia ou já foi pesquisada, terminar
	if(pesquisa_newkey == '' || pesquisa_key == pesquisa_newkey) {
		window.clearInterval(pesquisa_interval);
		pesquisa_interval = 0;
		if(pesquisa_newkey == '') {
			document.getElementById('procura_video_int2').style.display = 'none';
			pesquisa_mostra = false;
		}
		return;
	}
	
	// Incrementar tempo de pesquisa
	pesquisa_key_time++;
	
	if(pesquisa_key_time >= 10) {
		pesquisa_key_time = 0;
		tv_pesquisa(pesquisa_newkey);
	}
}

// Alteração do texto da pesquisa
function tv_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(tv_pesquisa_interval, 100);
	}
}


// Click no botão de pesquisa
function tv_search_bt_click() {

// Se a janela está aberta, fecha-la
	if(pesquisa_newkey == '' || pesquisa_mostra) {
		document.getElementById('procura_video_int2').style.display = 'none';
		pesquisa_mostra = false;
	}
	// Se a janela está fechada, abri-la e fazer a pesquisa
	else {
		document.getElementById('procura_video_int2').style.display = '';
		pesquisa_mostra = true;
		if(!pequisa_activa && (pesquisa_newkey != pesquisa_key))
			tv_pesquisa(pesquisa_newkey);
	}
}

// Efectuar uma nova pesquisa
function tv_pesquisa(key) {
	if(pequisa_activa) {
		return;
	}
	pesquisa_key = key;
	if(key == '') {
		document.getElementById('procura_video_int2').style.display = 'none';
		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/tv_pesquisa.php?canal='+canal+'&keyword='+encodeURIComponent(key)+'&'+Math.random(), true);   
	req.onreadystatechange = function (aEvt) {   
	  if (req.readyState == 4) {
		 pequisa_activa = false;
		 if(req.status == 200) {
			 var result_div = document.getElementById('procura_video_int2');
			 if(!result_div) {
				 alert("Erro ao mostrar resultados de pesquisa! Tente novamente!");
			 } else {
				 var html = '<table width="300" border="0" align="center" cellpadding="4" cellspacing="0">';
				 html = html + '<tr><td valign="top">&nbsp;</td><td align="left" valign="top">&nbsp;</td></tr>';
				 
				 // Resultado é devolvido no formato:
				 //  0     1           2         3      4     5      6       7    8
				 // id|thumbnail|data_registo|duracao|visto|votos|estrelas|nome|canal
				 var linhas = req.responseText.split("\n");
				 var tem_resultados = 0;
				 for(var i=0; i<linhas.length; i++) {
					 var colunas = linhas[i].split("|", 9);
					 var canal = colunas[8];
					 if(colunas[0] == '') break;
					 // Limitar a 5 resultados, o sexto mostra um link para ver os restantes resultados noutra página!
					 if(i == 5) {
						 html = html + '<tr><td>&nbsp;</td><td align="right" colspan="2" class="titulo3"><a href="tv_'+canal+'.php?pesquisa=1&canal='+canal+'&keyword='+encodeURIComponent(pesquisa_key)+'#resultados">ver todos os resultados</a></td></tr>';
						 break;
					 }
					 tem_resultados++;
					 //html = html + '<table width="310" border="0" cellpadding="0" cellspacing="0">\n';
					 html = html + '<tr><td width="80" rowspan="2" valign="top"><a href="tv_'+canal+'.php?id='+colunas[0]+'">';
					 html = html + '<img src="images/video/'+colunas[1]+'" width="80" height="46" border="0" /></a></td>\n';
					 html = html + '<td width="14" class="td3normalfont">&nbsp;</td>\n';
					 html = html + '<td colspan="2"><strong><a href="tv_'+canal+'.php?id='+colunas[0]+'" class="verdana12">'+colunas[7]+'</a></strong></td>\n';
					 html = html + '</tr><tr><td>&nbsp;</td>\n';
					 html = html + '<td><span class="td3normalfont">Data: '+colunas[2]+'<br />\n';
					 html = html + 'Duração: '+colunas[3]+'<br />Visto: '+colunas[4]+' xs <br />Votos: '+colunas[5]+'</span></td>\n';
					 html = html + '<td width="60" nowrap="nowrap">';
					 var e = parseInt(colunas[6]);
					 for(var j = 1; j <= 5; j++) {
						 if(e >= j) {
							 html = html + '<img src="imgs/video/estrela.gif" width="12" height="12" />';
						 } else {
							 html = html + '<img src="imgs/video/estrela_off.gif" width="12" height="12" />';
						 }
					 }
					 html = html + '</td></tr>\n'; //</table><br />\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('tv_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:tv_search_bt_click();">Fechar</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.display = '';
					 pesquisa_mostra = true;
				 }
			 }
		 } else {
		 	alert("Erro na pesquisa! Tente novamente!");
		 }
	  }
	};
	req.send(null);
}