
Livesearch = Class.create();

Livesearch.prototype = {
	initialize: function(attachitem, target, remove, url, pars, searchform, loaditem, searchtext) {
		this.attachitem = attachitem;
		this.target = target;
		this.remove = remove;
		this.url = url;
		this.pars = pars;
		this.searchform = searchform;
		this.loaditem = loaditem;
		this.searchtext = searchtext;
		this.t = null;  // Init timeout variable

		// Style the searchform for livesearch
		var inputs = $(searchform).getElementsByTagName('input');
		for (var i = 0; i < inputs.length; i++) {
			var el = inputs.item(i);
			if (el.type == 'submit')
				el.style.display = "none";
		}
		$(attachitem).className = 'livesearch';
		$(attachitem).setAttribute('autocomplete','off');
		$(attachitem).setAttribute('value', this.searchtext);
		Event.observe(attachitem, 'focus', function() { if ($(attachitem).value == searchtext) $(attachitem).setAttribute('value', '') });
		Event.observe(attachitem, 'blur', function() { if ($(attachitem).value == '') $(attachitem).setAttribute('value', searchtext) });

		// Bind the keys to the input
		Event.observe(attachitem, 'keyup', this.readyLivesearch.bindAsEventListener(this));
	},

	readyLivesearch: function(event) {
		var code = event.keyCode;
		var currentLivesearch = this;
		if (code == Event.KEY_ESC || ((code == Event.KEY_DELETE || code == Event.KEY_BACKSPACE) && $F(this.attachitem) == '')) {
			this.resetLivesearch();
		} else if (code != Event.KEY_LEFT && code != Event.KEY_RIGHT && code != Event.KEY_DOWN && code != Event.KEY_UP && code != Event.KEY_RETURN) {
			if (this.t) { clearTimeout(this.t) };
	        this.t = setTimeout(this.doLivesearch.bind(this), 400);
		}
	},

    doLivesearch: function() {

		new Ajax.Updater(
			this.target,
			this.url,
			{
				method: 'get',
				evalScripts: true,
				parameters: this.pars + $F(this.attachitem),
				onLoading: Effect.Appear(this.loaditem, {duration: .2})
		});
    },

	resetLivesearch: function() {
		$(this.attachitem).value = '';
		$(this.target).innerHTML = null;
		$(this.remove).style.display = null;
		initRollingArchives();
	}
}

Event.observe(window, "load", function() { new Livesearch('s', 'dynamiccontent', 'primarycontent', 'http://www.itais.net/wp-content/themes/k2/theloop.php', 'livesearch=1&s=', 'searchform', 'rollload', 'Teclea y espera para buscar'); } , false);
