
var KEY = {
	UP:			38,
	DOWN:		40,
	LEFT:		37,
	RIGHT:		39,
	PAGEUP:		33,
	PAGEDOWN:	34,
	ENTER:		13
};

var Search =  {
	value: '',

	init: function(options) {

		this.element = options.id;

		this.input = $(this.element).find(options.input);
		this.defalutValue = this.input.val();

		this.filtr = $(this.element).find(options.filtr);
		this.filtrInput = this.filtr.find("input[type=checkbox]");

		this.result = $(this.element).find(options.result);

		this.input.focus(function() {
			Search.focus();
		});

		this.input.focusout(function() {
			Search.blur();
		});

		this.input.bind($.browser.opera ? "keypress" : "keydown", function(event) {
			switch(event.keyCode) {
				case KEY.UP:
					break;
				case KEY.DOWN:
					event.preventDefault();
					if ($("#search_results").css('display') == 'block') {
						$(this).blur();
						$("#search_results").gadget('focus', 'on');
					}
					break;
				default:
					$("#search_results").hide();
					Search.value = Search.input.val();
					clearTimeout(Search.time);
					Search.time = setTimeout(function(){Search.keypress(event);}, 1000);
			}
		});

		$(this.filtrInput[0]).click(function() {
			if ($(this).attr('checked')) {
				Search.filtrInput.attr('checked', true);
			} else {
				Search.filtrInput.attr('checked', false);
			}
		});

		this.filtrInput.click(function() {
			if (!$(this).attr('checked')) {
				$(Search.filtrInput[0]).attr('checked', false);
			}
		});

		$("#search_options_button").click(function() {
			$("#search_options").toggle();
		});
	},

	focus: function() {
		if (this.input.val() == this.defalutValue) {this.input.val('');}
		this.input.addClass("search-hover");
	},

	blur: function() {
		if (this.input.val() == '') {this.input.val(this.defalutValue);}
		this.input.removeClass("search-hover");
	},

	keypress: function(event) {
		if (Search.value == Search.input.val()) {return;}

		if ( Search.req ) Search.req.abort();

		Search.req = $.ajax({
			type: 'POST',
			url: '/gadget/gadget.php?max=0&limit=4',
			data: $('form').serialize(),
			dataType: "json",
			success: function(data) {
				$("#search_results").gadget('clear');
				$("#search_results").gadget('options', {
					url: 		"/gadget/gadget.php",
					user_data:	Search.input.val(),
					data:		data
				});
				$("#search_results").gadget('reload');
				Search.req = null;
			}
		});

	},

	focusPanel: function() {
		$("#search_results").gadget('focus', 'off');
		this.input.focus();
	}

};


