var DefaultText = Class.create({
	initialize: function(element, text) { 
		element = $(element);
		text = text || '';
		this.type = DefaultText.getType(element);
		
		// Only allow this object to be set on a textarea or a password/text input field
		if (this.type == DefaultText.NONE)
		{
			throw new Error('Only a Text/Password input field or a Textarea is allowed');
		}

		this.element = element;
		
		// Use the text in the text field if no text is given
		this.text = (text.blank()) ? this.element.value : text;
		this.text.strip();
		
		this.element.observe('focus', this.onfocus.bindAsEventListener(this));
		this.element.observe('blur', this.onblur.bindAsEventListener(this));
		
		if (this.element.value.blank() || this.element.value.strip().toLowerCase() == this.text.toLowerCase()) {
			this.element.addClassName('default');
	
			this.active = true;
			
			if (this.type == DefaultText.PASSWORD) {
				try { this.element.type = 'text'; } catch (e) { }
			}
	
			setTimeout(this.setdefault.bind(this), 0); // "default" class needs some time to process				
		}
	},
	onfocus: function(event){
		if (!this.active) {
			return;
		}
		
		this.element.value = '';

		if (this.type == DefaultText.PASSWORD) {
			try { this.element.type = 'password'; } catch (e) { }
		}
		
		this.element.removeClassName('default');
	},
	onblur: function(event){
		if (this.element.value.blank()) {
			this.active = true;
			
			if (this.type == DefaultText.PASSWORD) {
				try { this.element.type = 'text'; } catch (e) { }
			}

			this.element.addClassName('default'); 
			setTimeout(this.setdefault.bind(this), 0); // "default" class needs some time to process
		} else {
			this.active = false;	
		}
	},
	setdefault: function() {
		this.element.value = this.text;
	}
});

Object.extend(DefaultText, {
	TEXTFIELD: 1,
	TEXTAREA: 2,
	PASSWORD: 3,
	NONE: 0,
	getType: function (element) {
		element = $(element);

		switch (element.tagName.toLowerCase()) {
			case 'input':
				switch (element.type.toLowerCase())	{
					case 'text':
						return DefaultText.TEXTFIELD;
					case 'password':
						return DefaultText.PASSWORD;
				}
				
				break;
			
			case 'textarea':
				return DefaultText.TEXTAREA;
		}
		
		return DefaultText.NONE
	}
});