var Searchfield = Class.create();
Searchfield.prototype = {
	initialize: function(element) {
		this.element = $(element);
		this.options = Object.extend({
			defaultvalue: 'Search for something...'
		}, arguments[1] || { });
		
		if (Prototype.Browser.WebKit)
			this.replaceWithAppleSearchfield();
		else
			this.decorateSearchfield();
	},
	
	replaceWithAppleSearchfield: function() {
		this.element.writeAttribute({
			type: 'search',
			placeholder: this.options.defaultvalue,
                      autosave: 'com.fluxiom.blog.search',
			results: 5
		});
	},
	
	decorateSearchfield: function() {
		this.element.value = this.options.defaultvalue;
		
		this.element.insert({ before: new Element('span', { id: 'searchfield_leftcap' }) });
		this.element.insert({ after: new Element('span', { id: 'searchfield_rightcap' }).addClassName('normal') });
		this.element.addClassName('decorated_searchfield');
		
		this.element.observe('focus', this.focus.bindAsEventListener(this));
		this.element.observe('blur', this.blur.bindAsEventListener(this));
		this.element.observe('keydown', this.keydown.bindAsEventListener(this));
	},
	
	focus: function() {
		if (this.element.value == this.options.defaultvalue) {
			this.element.value = '';
			this.element.addClassName('focus');
		}
	},
	
	blur: function() {
		if (this.element.value == '') {
			this.element.value = this.options.defaultvalue;
			this.element.removeClassName('focus');
		}
	},
	
	clear: function() {
		this.element.value = '';
		this.hideCancelLink();
		this.element.focus();
	},
	
	keydown: function() {
		var val = this.element.value;

		if (val == this.options.defaultvalue || val == '')
			this.hideCancelLink();
		else
			this.showCancelLink();			
	},
	
	showCancelLink: function() {
		var rightcap = $('searchfield_rightcap');
		rightcap.observe('click', this.clear.bindAsEventListener(this));
		rightcap.removeClassName('normal');
		rightcap.addClassName('cancel');
	},
	
	hideCancelLink: function() {
		var rightcap = $('searchfield_rightcap');
		rightcap.stopObserving('click');
		rightcap.removeClassName('cancel');
		rightcap.addClassName('normal');
	}
}

Event.observe(window, 'load', function() { 
   var searchfield = new Searchfield('q'); 
   if (Prototype.Browser.WebKit) $('q').setStyle({width:'200px'});
});