var ancien = "humpfpoursur";
var curpos = -1;
var $tf;
var $comp;

function debug(text)
{
	$("#debug").append("[Debug] "+text+"<br />");
}

function majList()
{
	$comp.find("table table tr").removeClass("active");
	$comp.find("table table tr:eq("+curpos+")").addClass("active");
	$tf.val($comp.find("table table tr:eq("+curpos+") td").text());
}

function setSelection(txt, idx, length)
{
    if (txt.createTextRange)
    {
        var range = txt.createTextRange();
        
        range.collapse(true);
        range.moveStart('character', idx);
        range.moveEnd('character', idx + length);
        range.select();
    }
    else if (txt.selectionEnd)
    {
        txt.selectionStart = idx;
        txt.selectionEnd = idx + length;
    }
}

function highlight(value, term)
{
	term = term.replace(/[AÀÁÂÃÄÅaàáâãäå]/, "[aàáâãäå]");
	term = term.replace(/[OÒÓÔÕÖØoòóôõöø]/, "[oòóôõöø]");
	term = term.replace(/[EÈÉÊËeéèêë]/, "[eéèêë]");
	term = term.replace(/[ÇçcC]/, "[ÇçcC]");
	term = term.replace(/[IÌÍÎÏiìíîï]/, "[iìíîï]");
	term = term.replace(/[UÙÚÛÜuùúûü]/, "[uùúûü]");
	term = term.replace(/[ÿÑñ]/, "[ÿñ]");
	return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
}

function checkTF()
{
	$tf = $("#auto");
	$comp = $("#complete");
	
	var active = true;
	
	$tf.focus();
	$tf.attr('autocomplete','off');
	$("#formsearch").attr('autocomplete','off');
	
	$tf.live("keydown",function(e)
	{
		if(e.keyCode == 13) //Entrée
		{
			e.preventDefault();
		}
	});
	
	$tf.live("keyup",function(e)
	{
		if(e.keyCode == 40) //Bas
		{
			if(curpos < $("tr").length - 1)
			{
				curpos++;
				majList();
				return;
			}
		}
		else if(e.keyCode == 38) //Haut
		{
			if(curpos > 0)
			{
				curpos--;
				majList();
				return;
			}
		}
		else if(e.keyCode == 13) //Entrée
		{
			if(curpos != -1)
			{
				//majList();
				//$comp.children("*").remove();
				doAction($comp.find("table table tr:eq("+curpos+")").attr('rel'));
				$comp.hide();
				return;
			}
		}		
		/*else if(e.keyCode == 13) //EntrÃ©e
		{
			if(curpos == -1) curpos = 0;
			majList();
			$comp.children("*").remove();
			e.preventDefault();
			return;
		}*/
		
		if(!active) return;
		
		if($(this).val().length > 2 && $(this).val() != ancien)
		{
			curpos = -1;
			ancien = $(this).val();
			$.get("dyn/moteur.php", {what:$(this).val()}, function(data)
			{
				results = unserialize(data);
				$comp.children("*").remove();
				if(data == "!;!")
				{
					$comp.append("<div style='color:white'><h2>Pas de résultat</h2></div>");
					$comp.fadeIn(300);
					$comp.css("height","auto");
				}
				else
				{
					var sortie = "<table style='width:100%;'>";
					
					for(var i = 0; i < results.length; i++)
					{
						if(results[i][0] != undefined) sortie += "<tr><td><h2><span>"+results[i][0]+"</span></h2><table style='width:100%;'>";
						for(var j = 1; j < results[i].length; j++)
						{
							if(results[i][j] != "")
							{
								var theresult = results[i][j][1];
								if(results[i][j].length > 2) theresult += " "+results[i][j][2];
								theresult = highlight(theresult, $tf.val());
								sortie += "<tr rel='"+results[i][j][0]+"'><td>"+theresult+"</td></tr>";
							}
						}
						sortie += "</table></td></tr>";
					}
					sortie += "</table>";
					$comp.append(sortie);
					
					if(0) //Non utilisÃ©
					{
						if(num_result == 1)
						{
							var anc_val = $tf.val();
							var newval = results[0][0][1]+" "+results[0][0][2];
							$tf.val(newval);
							setSelection($tf.get(0), newval.length, 0);
						}
						$comp.hide();
					}
					else $comp.fadeIn(300);
					
					$comp.css("height","auto");
					if($comp.height() > 480)
					{
						$comp.height(480);
						$comp.width($comp.width() + 30);
						$comp.css('overflow','auto');
					}
					else $comp.css('overflow','visible');
					
					var $tds = $comp.find("table table tr");
					$tds.css('cursor','pointer');
					$tds.hover(function()
					{
						$(this).addClass('active');
					}, function()
					{
						$(this).removeClass('active');
					});
					$tds.click(function()
					{
						doAction($(this).attr('rel'));
					});
				}
			});
		}
	});
	
	$tf.blur(function()
	{
		setTimeout(fade, 2);
	});
	
	$tf.focus(function()
	{
		$comp.fadeIn(300);
	});
	
	function fade()
	{
		$comp.fadeOut(300);
	}
}

var sep = ["!;!","@p@","t-t","e!e","a%a"];

function doAction(act)
{
	debug("Doing "+act);
	act = act.split("_");
	if(act[0] == "spec")
	{
		loadUniq(parseInt(act[1]));
	}
	else if(act[0] == 'classic')
	{
		loadContent("dyn/classic.php?idnav="+act[1]+"&");
	}
	else if(act[0] == 'orch' || act[0] == 'orch-inv')
	{
		loadContent("orchestre_03_01.htm", function()
		{
			goto(-1, 1);
			setTimeout(function()
			{
				if (act[0] == 'orch')
				{
					goto(1, 0);
				}
				else
				{
					goto(1, 1);
				}
				setTimeout(function()
				{
					$("a").each(function()
					{
						if($(this).attr('href') == "orchestre_info_"+act[1]+".htm" && act[0] == 'orch' || $(this).attr('href') == "invites_info_"+act[1]+".htm" && act[0] == 'orch-inv')
						{
							$(this).click();
						}
					});
				}, 500);
			}, 500);
		});
	}
}

function unserialize(string, level)
{
	if (level == undefined) level = 0;
	
	var temp = string.split(sep[level]);
	for(var i = 0; i < temp.length; i++)
	{
		if(temp[i] != "")
		{
			if(string.indexOf(sep[level + 1]) != -1)
			{
				var a = unserialize(temp[i], level + 1);
				temp[i] = a;
			}
		}
	}
	return temp;
}