/**
 * @author reinderdevries
 */
var ajaxDelayTimer = 0;

var onQueryChanged = function()
{
	if($('#query').val() == '')
	{
		$('#suggest').html('');
	} else {
		clearTimeout(ajaxDelayTimer);
		ajaxDelayTimer = setTimeout(ajaxSuggestRequest, 200);	
	}
}

var ajaxSuggestRequest = function()
{
	var query = $('#query').val();
	if (query.length > 0) 
	{
		$.get('http://www.bijsluiterwoordenboek.nl/action/ajax/query/' + query, onSuggestHandler);
	} else if(query.length == 0) {
		$('#suggest').html('');
	}
}

var onSuggestHandler = function(data)
{
	$('#suggest').html('');
	var list = jQuery.parseJSON(data);
	var num = (window != window.top) ? 1 : list.length;
	
	if(list.length > 0)
	{
		for(var i = 0; i < num; i++)
		{
			var item = document.createElement('a');
			item.href = 'http://www.bijsluiterwoordenboek.nl/action/search/q/' + escape(list[i]);
			item.innerHTML = list[i];
			
			if(window != window.top)
				item.target = "_blank";
			
			$('#suggest').append(item);
		}
	}
	
	document.getElementById('suggest').style.display = 'block';
	
}

var onQuerySubmit = function()
{
	if(window != window.top)
	{
		// iframe
		window.open('http://www.bijsluiterwoordenboek.nl/action/search/q/' + document.getElementById('query').value, "_blank");
	} else {
		// normal.
		document.location = 'http://www.bijsluiterwoordenboek.nl/action/search/q/' + document.getElementById('query').value;
	}
}

window.onload = function()
{
	$('#query').keyup(onQueryChanged);
	$('#submit').bind('click', onQuerySubmit);
	$('input[name=q]').bind('keypress', function(e) {
		
		if(e.keyCode == "13")
		{
			e.preventDefault();
			this.blur();
			onQuerySubmit();
		}
	});
	
	if(window != window.top)
	{
		// Running from iFrame
		var fileref=document.createElement("link")
		fileref.setAttribute("rel", "stylesheet")
		fileref.setAttribute("type", "text/css")
		fileref.setAttribute("href", "http://www.bijsluiterwoordenboek.nl/inc/style/embed.css");
		document.getElementsByTagName("head")[0].appendChild(fileref);
		
		var width = (typeof window.innerWidth != 'undefined') ? window.innerWidth : document.getElementsByTagName('body')[0].clientWidth;
		//width = Math.round(width / 100) * 100;
		
		if(width == 0)
			width = 250;
		
		
		document.getElementById("logo").src = "http://www.bijsluiterwoordenboek.nl/img/gui/logo_" + width + ".png";
		document.getElementById("query").style.width = (width - 120) + "px";
		document.getElementById("suggest").style.width = (width - 113) + "px";
		document.getElementById("page").style.width = (width - 20) + "px";
		document.getElementById("submit").onClick = onQuerySubmit;
	}
	$('body').click(function() { $('#suggest').html(''); });
}

