/**************************************************************************************
	TooltipInside
	=============
	by Pixelindustries (2009)
	
	for more information / license information, please contact me/us
**************************************************************************************/

var TooltipInside = new Class({
	
	Implements: Options,
	
	supportTypeSwitching: true,
	
	options: {
		grayClass: 'gray'
	},
	
	initialize: function(options) {
		this.setOptions(options);
		if ((Browser.Engine && Browser.Engine.trident) || Browser.ie) {
			this.supportTypeSwitching = false;
		}
		this.attach();
	},
	
	
	// attach()
	// --------
	// attach to input elements
	// can also be called after an ajax request to work on newly created inputs
	
	attach: function() {
		var that = this;
		
		$$('input[type=text][title], input[type=password][title], textarea[title]')
			.each(function(elm) {
			
				// prevent double attachment
				if(elm.retrieve('tooltipped')) return;
				elm.store('tooltipped', true);
				
				// on parent form submit, prevent title submission
				var parent_form = elm.getParent('form');
				if (parent_form) {
					parent_form.addEvent('submit', function(e) {
						if (elm.hasClass(that.options.grayClass)) {
							elm.set('value', '');
							elm.removeClass(that.options.grayClass);
						}
					});
				}
				
				// type-switching makes the script work even for password fields (!) 
				if (that.supportTypeSwitching) {
					elm.store('originaltype', elm.get('type'));
				}
				
				// initial color
				if (elm.get('value') == '' || elm.get('value') == elm.get('title')) {
					elm.set('value', elm.get('title')).addClass(that.options.grayClass);
					if (that.supportTypeSwitching && elm.get('type') == 'input' ) {
						elm.setProperty('type', 'text');
					}
				}
				
				// behaviour
				elm.addEvents({
					'focus': function(e) {
						var input = e.target;
						if (input.get('value') == input.get('title')) {
							input.set('value', '').removeClass(that.options.grayClass);
							if (that.supportTypeSwitching && this.get('type') == 'input' ) {
								input.setProperty('type', input.retrieve('originaltype'));
							}
						}
					},
					'blur': function(e) {
						var input = e.target;
						if (input.get('value') == '') {
							input.addClass(that.options.grayClass).set('value', input.get('title'));
							if (that.supportTypeSwitching && this.get('type') == 'input') {
								input.setProperty('type', 'text')
							}
						}
					}
				});
		});
	}
});
