var Search = new Class({
	initialize: function() {
		// Fetch search input
		this.search = $(document.body).getElement('input.search');
		// Create events
		this.events();
	},
	events: function() {
		var obj = this;
		this.search.addEvents({
			// On each keyup, return results
			'keyup': function(input) {
				// Only if value's lenght is more than 2
				if (this.get('value').length>2) {
					obj.request = new Request.HTML({
						url: '/sync/search/?lang='+language+'&color='+colour+'&search='+obj.search.get('value'), 
						link: 'cancel',
						onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript) {
							// Delete previous results
							if ($chk($(document.body).getElement('div.search')))
								$(document.body).getElement('div.search').destroy();
							// Inject results
							var results = new Element('div', {'class': 'search', 'html': responseHTML}).inject($(document.body));
							obj.search.focus();
							// Place div result search
							results.setStyle('left', obj.search.getCoordinates().left.toInt()-103);
							// Add event
							results.addEvents({
								'mouseenter': function() { this.store('mouse', 'true'); },
								'mouseleave': function() { this.store('mouse', 'false'); }
							});
						}
					}).send();
				} else if ($chk($(document.body).getElement('div.search'))) {
					$(document.body).getElement('div.search').destroy();
				}
			},
			// On focus, set border to proper color
			'focus': function() {
				this.setStyle('border-color', '#'+colour);
				// Check results again if input search is not empty
				if (this.get('value')!='' && $defined(obj.request)) obj.request.send();
			},
			// On blur, only if mouse if not hovering results
			'blur': function() {
				if ($chk($(document.body).getElement('div.search')) && $(document.body).getElement('div.search').retrieve('mouse')=='true') {
					obj.search.focus();
				} else {
					this.setStyle('border-color', '#333');
					if ($chk($(document.body).getElement('div.search')))
						$(document.body).getElement('div.search').destroy();
				}
			}
		});
	}
});

window.addEvent('domready', function() { new Search(); });
