var HoverFix = Class.create({
		
	init:function(id) {
		this.id = id;
		this.hover();
	},
	
	hover:function() {
		// clobbers current mouse over/out, but I'm okay with that
		
		$(this.id).onmouseover = function() {
			$(this.id).addClassName('hover');
		};
		$(this.id).onmouseout = function() {
			$(this.id).removeClassName('hover');
		};
	}
	
});

var SearchField = Class.create({
	
	init:function(id, defaultQuery) {
		// initialize vars
		this.id = id;
		this.defaultQuery = defaultQuery;
		this.searchFieldValue = $F(id);
		
		// fill the search field
		this.fill();
		
		// observe focus and blur
		$(id).observe('focus', this.toggle.bind(this));
		$(id).observe('blur', this.toggle.bind(this));
	},
	
	setFieldValue:function() { this.searchFieldValue = $F(this.id); },
	
	clean:function() { $(this.id).value = ""; },
	
	fill:function() { $(this.id).value = this.defaultQuery; },
	
	toggle:function(event) {
		this.setFieldValue();

		if (this.searchFieldValue == '' && event.type == 'blur') {
			this.fill();
			$(this.id).removeClassName('focus'); // for IE
		}
		else if (this.searchFieldValue == this.defaultQuery && event.type == 'focus') {
			this.clean();
			$(this.id).addClassName('focus'); // for IE
		}
		else if (event.type == 'focus') {
			$(this.id).select(); // I wish this worked in Safari :(
			$(this.id).addClassName('focus'); // for IE
		}
		else if(event.type == 'blur') {
			$(this.id).removeClassName('focus'); // for IE
		}
	}
		
});

document.observe('dom:loaded', function() {
	var search_field = new SearchField();
	search_field.init('query', 'search');
	
	// fix hover states for IE
	if (window.attachEvent) {
		var hover_fix = new HoverFix();
		hover_fix.init('search');
	}
});
