/*
* Siete search
* @Author: Alexander Gavazov
* @Site: www.studio.bg
*/


var Search = function(parameters)
{
	this.field = parameters.field;
	this.resultsContainer = parameters.resultsContainer;

	this.timer = '';
	this.results = '';

	this.setBehaviour();
}

Search.prototype.setBehaviour = function()
{
	this.resultsContainer.hide();
	this.field.onfocus = this.setResult.bind(this);
	this.field.ondblclick = this.doQuery.bind(this);
	this.field.onblur = function() { setTimeout(this.hide.bind(this), 200) }.bind(this);
	this.field.onkeyup = this.search.bind(this);
}

Search.prototype.hide = function()
{
	clearTimeout(this.timer);
	this.results = '';
	this.resultsContainer.update();
	this.resultsContainer.hide();
}

Search.prototype.search = function()
{
	clearTimeout(this.timer);
	this.timer = setTimeout(this.doQuery.bind(this), 600);
}

Search.prototype.doQuery = function()
{
	// Ajax
	new Ajax.Request(root_directory + lang + '/ajax/search_complete', {
		method: 'post',
		parameters: 'q=' + this.field.value.strip(),
		onComplete: function(req) {
			this.results = req.responseText;
			this.setResult();
		}.bind(this)
	});
}

Search.prototype.setResult = function()
{
	if(this.results)
	{
		this.resultsContainer.show();
		this.resultsContainer.update(this.results);
		this.setResultBehaviour();
	}
	else
	{
		this.resultsContainer.hide();
	}
}

Search.prototype.setResultBehaviour = function(obj)
{
	this.resultsContainer.childElements().each(function(node) {
		var node = node;
		node.onclick = function()
		{
			this.field.value = node.innerHTML.replace(/<(?:.|\s)*?>/g, '');
			this.results = '';
		}.bind(this);
	}.bind(this));
}